C#:减去双打的奇怪结果 [英] C#: Weird outcome when subtracting doubles
问题描述
可能重复:
为什么C#中的浮点算术不精确?
我一直在处理一些数字和C#,下面的代码行的结果与预期的数字不同:
I have been dealing with some numbers and C#, and the following line of code results in a different number than one would expect:
double num = (3600.2 - 3600.0);
我希望num为0.2,但原来是0.1999999999998181。是否有任何理由为什么生产一个关闭但仍然不同的十进制?
I expected num to be 0.2, however, it turned out to be 0.1999999999998181. Is there any reason why it is producing a close, but still different decimal?
推荐答案
这是因为 double
是一个浮点数据类型。
This is because double
is a floating point datatype.
如果你想要更高的精度,你可以切换到使用 decimal
If you want greater accuracy you could switch to using decimal
instead.
decimal
的文字后缀是m,所以要使用十进制
算术(并产生一个十进制
结果)您可以将代码写入
The literal suffix for decimal
is m, so to use decimal
arithmetic (and produce a decimal
result) you could write your code as
var num = (3600.2m - 3600.0m);
请注意,使用 decimal
。它是一个128位数据类型,而不是64位,它的大小是 double
。这使得在内存和处理方面都更加昂贵。它的范围比 double
小得多。
Note that there are disadvantages to using a decimal
. It is a 128 bit datatype as opposed to 64 bit which is the size of a double
. This makes it more expensive both in terms of memory and processing. It also has a much smaller range than double
.
这篇关于C#:减去双打的奇怪结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!