添加浮点数不会产生正确的结果 [英] Adding floats does not yield a correct result
问题描述
想象一下以下情况。
循环中将金额加到总计中:
Imagine the following situation. Amounts are added to a total in a loop:
float total = 0;
float[] amounts = new float[]{...};
foreach(float amount in amounts)
{
total += amount;
}
总计
,为因为所有金额
都已写入数据库。
当我在SQL中计算 SUM(amount)
时,它得出的值不同于总计
。
而且,当我在C#中执行相同的计算时,但是这次将金额加到类型double的值上,
total
, as wel as all the amount
s are written to a database.
When I calculate SUM(amount)
in SQL, it results in a value that differs from total
.
Moreover, when I do the same calculation in C#, but this time adding the amounts to a value of type double,
double total = 0;
//the rest of the code is the same as above
然后是 total
代表正确的值。
这可能是由浮点数和双精度数之间的精度差异引起的吗?
Could this be caused by the difference in precision between a float and a double?
请注意,这取决于值。此计算的大多数结果 是正确的。
Note that it depends on the values. Most of the results of this calculation are correct.
推荐答案
是。 SQL Server的浮点大小是不同的,但数据库中可能有8个字节的浮点。当您在C#代码中使用double(8字节)时,结果是相同的,而当使用float(4字节)时,结果却不同。浮点值范围内的double值将与浮点值不同。
Yes. SQL Server's float size is variant but you likely have 8 byte floats in the database. When you use doubles ( 8 bytes ) in the C# code the results are the same, when you use floats ( 4 bytes ) they're different. double values within the range of a float will not be the same as the float values.
这篇关于添加浮点数不会产生正确的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!