问题描述
我有一个名为 x
的 double
变量.在代码中,x
被分配了一个 0.1
的值,我在比较 x
和 0.1
I've a
double
variable called x
.In the code, x
gets assigned a value of 0.1
and I check it in an 'if' statement comparing x
and 0.1
if (x==0.1)
{
----
}
可惜没有进入
if
语句
我应该使用
Double
还是double
?
这背后的原因是什么?你能为此提出一个解决方案吗?
What's the reason behind this? Can you suggest a solution for this?
推荐答案
由于计算机如何存储浮点值,这是一个标准问题.在此处搜索浮点问题",您会发现大量信息.
It's a standard problem due to how the computer stores floating point values. Search here for "floating point problem" and you'll find tons of information.
简而言之 – 浮点数/双精度数无法精确存储
0.1
.它总是会有点偏差.
In short – a float/double can't store
0.1
precisely. It will always be a little off.
您可以尝试使用以十进制表示法存储数字的
decimal
类型.因此 0.1
将可以精确表示.
You can try using the
decimal
type which stores numbers in decimal notation. Thus 0.1
will be representable precisely.
您想知道原因:
Float/double 存储为二进制分数,而不是十进制分数.举例说明:
Float/double are stored as binary fractions, not decimal fractions. To illustrate:
12.34
十进制表示法(我们使用的)表示
12.34
in decimal notation (what we use) means
1 * 10 + 2 * 10 + 3 * 10 + 4 * 10
计算机以相同的方式存储浮点数,除了它使用基数
2
:10.01
表示
The computer stores floating point numbers in the same way, except it uses base
2
: 10.01
means
1 * 2 + 0 * 2 + 0 * 2 + 1 * 2
现在,您可能知道有些数字无法用我们的十进制表示法完全表示.例如,十进制的
1/3
是0.3333333…
.同样的事情发生在二进制表示法中,只是不能精确表示的数字是不同的.其中有数字1/10
.在二进制符号中,0.000110011001100…
.
Now, you probably know that there are some numbers that cannot be represented fully with our decimal notation. For example,
1/3
in decimal notation is 0.3333333…
. The same thing happens in binary notation, except that the numbers that cannot be represented precisely are different. Among them is the number 1/10
. In binary notation that is 0.000110011001100…
.
由于二进制表示法无法精确存储,因此以四舍五入的方式存储.因此你的问题.
Since the binary notation cannot store it precisely, it is stored in a rounded-off way. Hence your problem.
这篇关于在 C# 中比较双精度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!