【问题标题】:C# floating point number's precision of display and calculation, which are differentC#浮点数的显示精度和计算精度不同
【发布时间】:2014-03-12 22:29:59
【问题描述】:

我在 Win7 上使用 C# 进行计算。

我遇到了双精度问题。

 double x = 3389774.583;

 string ss = "x is " + x + " x square is " + x * x + " , 11490571723552.8 - x*x is " + (11490571723552.8 - x * x) + "\n";

 Console.WriteLine(ss);

你可能会发现结果不是 0 甚至很难 11490571723552.8 是 x*x。

我知道是显示和计算的精度问题。

我可以设置一个阈值,使结果为0。

还有其他更好的方法吗?

谢谢

【问题讨论】:

标签: c# c#-4.0 floating-accuracy floating-point-precision


【解决方案1】:

这是因为 3389774.583 的平方不是 11490571723552.8。 如果您尝试使用 windows 计算器,您将获得大约 11490571723552.823889 的值。

所以没有机会得到 (11490571723552.8 - x * x) 的结果 0,其中 x 是 3389774.583

试试

double x = 3389774.583;
double xx = x*x;
Console.WriteLine(xx); 

string ss = "x is " + x + " x square is " + x * x + " , 11490571723552.8 - x*x is " + (xx - x * x) + "\n";
Console.WriteLine(ss); 

【讨论】:

    【解决方案2】:

    尝试使用format 字符串将输出四舍五入为小数位数:

    Console.WriteLine(ss.ToString("F2"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-05
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      相关资源
      最近更新 更多