你好,我在 C# 中有这段代码:
float n = 2.99499989f;
MessageBox.Show("n = " + n.ToString("f2", CultureInfo.InvariantCulture));
C++ 中的这段代码:
float n = 2.99499989f;
printf("n = %.2f", n);
第一个输出3.00。
第二个一个输出2.99。
我不知道为什么会这样。
更新:
我还尝试了 Objective-C NSLog,输出是 2.99。
我需要快速修复它,所以我使用了以下方法:
float n = 2.99499989f;
float round = (float)Math.Round(n, 2);
MessageBox.Show("round = " + round.ToString(CultureInfo.InvariantCulture));
此代码显示 2.99,但以 double 计算舍入。我找不到 Math.RoundF。
最佳答案
使用 BitConverter.GetBytes
并打印出实际产生的字节表明这不是编译器的区别 - 在这两种情况下,实际存储的浮点值是 0x403FAE14
,this handy calculator告诉我是准确值
2.99499988555908203125
因此,区别必须在于 printf
和 ToString
的不同行为。不止于此,我不能马上说。
关于c# - ToString ("f2"中的 .NET 舍入错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2085449/