变量精度
precision in variables
我在执行计算和比较结果时遇到变量精度问题。我在 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)”
这个问题有简单的解决方法吗?
您不应该使用 == 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.");
我在执行计算和比较结果时遇到变量精度问题。我在 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)”
这个问题有简单的解决方法吗?
您不应该使用 == 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.");