【问题标题】:precision in variables变量精度
【发布时间】:2021-02-12 10:34:00
【问题描述】:

在执行计算和比较结果时,变量的精度存在问题。我在 C# 中工作。这是一个例子。

double ImporteDebe;
ImporteDebe = 0;
double base1;
base1 = Convert.ToDouble("10,22");
double PorcentajeIva1;
PorcentajeIva1 = Convert.ToDouble("0,21");
double Iva1;
Iva1 = Convert.ToDouble((base1 * PorcentajeIva1).ToString("N2")); //2,1462 -> 2,15

ImporteDebe = ImporteDebe + base1; // 10,22
ImporteDebe = ImporteDebe + Iva1;// 10,22 + 2,15 = 12,37000000001

if (ImporteDebe == (base1 + Iva1))
{
    System.Diagnostics.Debug.Print(Convert.ToString(ImporteDebe));//condition is never met
}

如果您运行代码,您会发现条件“ImporteDebe == (base1 + Iva1)”从未满足

这个问题有简单的解决方案吗?

【问题讨论】:

  • 对我来说很好;你确定吗?
  • 如果没有特别要求双精度,请尝试使用十进制。
  • 我正在使用 Visual Studio 17 和 C#。它对我不起作用。条件“ImporteDebe==base1+Iva1”永远不会满足。
  • 使用十进制变量可以正常工作。使用与可执行文件相关的十进制而不是双精度?执行的规模或速度?

标签: c# variables double


【解决方案1】:

你不应该使用== operator比较双打

而是像官方文档中的 here:

// Initialize two doubles with apparently identical values
double double1 = .333333;
double double2 = (double) 1/3;
// Define the tolerance for variation in their values
double difference = Math.Abs(double1 * .00001);

// Compare the values
// The output to the console indicates that the two values are equal
if (Math.Abs(double1 - double2) <= difference)
   Console.WriteLine("double1 and double2 are equal.");
else
   Console.WriteLine("double1 and double2 are unequal.");

【讨论】:

  • 一般来说非常好的建议,但是问题中的代码应该仍然可以工作,因为双方的值都被计算为10.22 + 2.15
  • 但它们可能最终会略有不同,具体取决于 CPU 或使用的编译器,甚至是构建配置。这个答案是正确的
猜你喜欢
  • 2013-09-06
  • 1970-01-01
  • 1970-01-01
  • 2011-12-12
  • 1970-01-01
  • 1970-01-01
  • 2012-12-26
  • 1970-01-01
  • 2018-05-09
相关资源
最近更新 更多