【发布时间】:2013-06-28 21:23:40
【问题描述】:
想象以下情况。 金额在循环中添加到总数中:
float total = 0;
float[] amounts = new float[]{...};
foreach(float amount in amounts)
{
total += amount;
}
total,以及所有amounts 都写入数据库。
当我在 SQL 中计算 SUM(amount) 时,它产生的值与 total 不同。
此外,当我在 C# 中进行相同的计算,但这次将金额添加到 double 类型的值时,
double total = 0;
//the rest of the code is the same as above
那么total代表正确的值。
这可能是由于浮点数和双精度数的差异造成的吗?
请注意,这取决于值。这个计算的大部分结果是正确的。
【问题讨论】:
-
float 类型的变量只有 7 位精度,而 double 类型的变量有 15 位精度。
-
向我们展示花车,然后我们就可以提供帮助...?
-
@newStackExchangeInstance:值是随机的(不像“随机生成”,但它们可以是任何值)
标签: c# .net double floating-accuracy