3

我试图四舍五入我的价值观,如果它是0.5或更大,它变成1,否则它变成0。例如:

3.7 -> 4;
1.3 -> 1;
2.5 -> 3;
...

有任何想法吗?

4

4 回答 4

7
Math.Round(3.7,MidpointRounding.AwayFromZero);

http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx

在上面,我使用了AwayFromZerofor rounding,因为默认是 Banker 的四舍五入,所以如果小数为 0.5,则四舍五入到最接近的偶数。所以 3.5 变成 4(最接近的偶数),但 2.5 变成 2(最接近的偶数)。因此,您选择如上所示的不同方法来制作 3.5 到 4 和 2.5 到 3。

于 2011-10-23T04:50:03.613 回答
3

最简单的方法是将 0.5 添加到输入,然后转换为 int。

于 2011-10-23T04:51:23.743 回答
2

我最后一个到达,所以我会告诉一些不同的东西。你舍得0.51使用double!使用decimals。double拥有“确切”数字并不好。

启动这段代码并玩得开心(请注意,像 0.49999999999999994 这样的数字在单声道中存在/曾经存在“错误”,因此要在 ideone 上运行它,我必须对其进行一些修改以尝试绕过 1.5:http://ideone .com/57XAYV

public static void Main()
{
    double d = 1.0;
    d -= 0.3;
    d -= 0.2;

    Console.WriteLine("Standard formatting: {0}", d); // 0.5
    Console.WriteLine("Internal Representation: {0:r}", d); // 0.49999999999999994
    Console.WriteLine("Console WriteLine 0 decimals: {0:0}", d); // 1
    Console.WriteLine("0 decimals Math.Round: {0}", Math.Round(d, MidpointRounding.AwayFromZero)); // 0
    Console.WriteLine("15 decimals then 0 decimals Math.Round: {0}", Math.Round(Math.Round(d, 15, MidpointRounding.AwayFromZero), MidpointRounding.AwayFromZero)); // 1
}
于 2011-10-23T06:32:48.673 回答
0

围捕

Math.Round(3.5, 0, MidpointRounding.AwayFromZero) -> 4

四舍五入

Math.Round(3.5, 0, MidpointRounding.ToEven) -> 3
于 2020-07-13T10:06:39.903 回答