C#乘法错误(双精度)[从C#论坛转发]
问题描述:
当我做一些简单的事情时,例如
When I do some thing simple like
double result = 3.1*4.1;
结果是12.709999999999999
我本来希望12.710000000000000
the result is 12.709999999999999
I would have expected 12.710000000000000
Is this normal for C#?
答
这是正常的,浮点数不能始终表示值的准确表示.如果要显示四舍五入的数字,则ToString()
方法提供了该功能.
This is normal, floating point numbers cannot always depict an accurate representation of a value. If you want to display the number rounded then the ToString()
method offers that capability.
有一个经典文本, ^ ]应该可以帮助您了解此处发生的情况.它并非特定于C#,而是针对C#使用的浮点数的IEEE 754标准.
可以说,这是正常现象,只是一个常见的舍入错误,类似于您尝试在小数形式表示诸如10 / 3
之类的表达式的结果时在小学时遇到的错误. .
There is a classic text, What Every Computer Scientist Should Know About Floating-Point Arithmetic[^] by David Goldberg that should help you understand what''s happening here. It''s not specific to C#, but rather the IEEE 754 standard for floating-point numbers that C# uses.
Suffice to say, it is normal, merely a common rounding error, similar to what you might have encountered in grade school when trying to represent the result of an expression such as10 / 3
in decimal form...
我遇到了同样的问题.我发现的唯一解决方案是将值转换为小数,然后将它们相乘,然后转换为Double.那是昂贵的,但是如果没有其他解决方案可用,那就可以接受.
I had the same problem. The only solution I found is to convert the values to decimals, multiply them and after that convert to Double. That''s expensive, but if no other solution is available, is acceptable.