在C#中比较双重价值 [英] Comparing double values in C#
问题描述
我使用C#。
我有一个名为x的双变量。 在code,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语句
Unfortunately it does not enter the if statement
1)我应该使用双或双???
1) Should I use Double or double???
2)什么是这背后的原因是什么?您能否提供一个解决方案吗?
2) 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 precisely。这将永远是一个有点过。
In short - a float/double can't store 0.1 precisely. It will always be a little off.
您可以尝试使用十进制
键入存储号码十进制格式。因此,0.1将重新presentable precisely。
You can try using the decimal
type which stores numbers in decimal notation. Thus 0.1 will be representable precisely.
您想知道的原因:
浮点/双精度都为二进制小数,不是小数存储。为了说明:
Float/double are stored as binary fractions, not decimal fractions. To illustrate:
在十进制形式12.34(我们使用的)是指1 * 10 1 + 2 * 10 0 + 3 * 10 1 + 4 * 10 -2 。计算机存储浮点数以相同的方式,除了使用基材2:10.01装置1 * 2 1 + 0 * 2 0 + 0 * 2 - 1 + 1 * 2 -2
12.34 in decimal notation (what we use) means 1*101+2*100+3*10-1+4*10-2. The computer stores floating point numbers in the same way, except it uses base 2: 10.01 means 1*21+0*20+0*2-1+1*2-2
现在,你可能知道,有一些不能被重新$ P $的一些数字与我们的十进制形式psented充分。例如利用十进制表示的三分之一是0.3333333 ...同样的事情发生在二进制表示法不同之处在于,不能pcisely重新presented $ P $的数字是不同的。其中之一是数量的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...
由于二进制符号不能存储它precisely,它被存储在一个倒圆的方式。因此,你的问题。
Since the binary notation cannot store it precisely, it is stored in a rounded-off way. Hence your problem.
这篇关于在C#中比较双重价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!