【发布时间】:2010-01-18 10:58:58
【问题描述】:
您好,我在 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,但以双精度计算舍入。我找不到 Math.RoundF。
【问题讨论】:
标签: c# c++ rounding-error