📌  相关文章
📜  如何在数组c#中四舍五入到最接近的数字(1)

📅  最后修改于: 2023-12-03 15:24:38.641000             🧑  作者: Mango

如何在数组c#中四舍五入到最接近的数字

在C#中,我们可以使用Math.Round()方法将数字四舍五入到最近的整数。但是,如果我们想将一个数组中的所有数字四舍五入到最近的整数该怎么办?在本文中,我们将介绍如何在数组c#中四舍五入到最接近的数字。

示例程序

以下是一个简单的示例程序,它将一个数组中的所有数字四舍五入到最近的整数:

using System;

class Program
{
    static void Main(string[] args)
    {
        double[] numbers = { 1.1, 2.2, 3.3, 4.4, 5.5 };
        int[] roundedNumbers = new int[numbers.Length];

        for (int i = 0; i < numbers.Length; i++)
        {
            roundedNumbers[i] = (int)Math.Round(numbers[i]);
        }

        Console.WriteLine(string.Join(", ", roundedNumbers));
    }
}

在此示例中,我们定义了一个包含5个double类型数字的数组。我们创建了一个新的整数数组,该数组的长度与数字数组相同。使用for循环迭代数字数组中的所有数字,并使用Math.Round()方法将每个数字四舍五入到最近的整数。

最后,我们使用Console.WriteLine()方法将结果输出到控制台。

代码解释

现在让我们逐行分析以上示例代码:

using System;

我们需要使用Math.Round()方法,因此需要包含System命名空间。

class Program
{
    static void Main(string[] args)
    {
        double[] numbers = { 1.1, 2.2, 3.3, 4.4, 5.5 };
        int[] roundedNumbers = new int[numbers.Length];

        for (int i = 0; i < numbers.Length; i++)
        {
            roundedNumbers[i] = (int)Math.Round(numbers[i]);
        }

        Console.WriteLine(string.Join(", ", roundedNumbers));
    }
}

我们定义了一个名为Program的类,其中包含一个Main()方法。在Main()方法中,我们创建了一个包含5个double类型数字的数组numbers。我们还创建了一个新的整数数组roundedNumbers,该数组的长度与数字数组相同。

使用for循环迭代数字数组中的所有数字,并使用Math.Round()方法将每个数字四舍五入到最近的整数(在这种情况下,我们将其强制转换为int类型)。将结果存储在新的整数数组roundedNumbers中。

最后,我们使用Console.WriteLine()方法将结果输出到控制台,并使用string.Join()方法将数组中的所有数字连接为一个字符串。

结论

使用Math.Round()方法,我们可以将数组中的所有数字四舍五入到最接近的整数。这可以用于各种应用程序,例如计算平均值或舍入货币值。