比较C#中的double值 [英] Comparing double values in C#

查看:982
本文介绍了比较C#中的double值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#。



我有一个名为x的double变量。
在代码中,x被赋值为0.1,我在一个'if'语句中比较x和0.1

  if(x == 0.1)
{
----
}

不幸的是它没有输入if语句



1)我应该使用Double还是double ???



2)这是什么原因?你可以为此建议一个解决方案吗?

解决方案

由于计算机如何存储浮点值,这是一个标准问题。在这里搜索浮点问题,你会发现大量的信息。



简而言之,float / double不能精确地存储0.1。它将永远是一点点。



您可以尝试使用以十进制格式存储数字的 decimal 类型。因此,0.1将正确地表示。






您想知道原因:



浮点数/双倍存储为二进制分数,而不是十进制分数。说明:



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



现在,你可能知道有一些数字不能用我们的十进制符号。例如,十进制格式的1/3是0.3333333 ...同样的事情发生在二进制符号中,除了不能精确表示的数字是不同的。其中有1/10。以二进制表示法为0.000110011001100 ...



由于二进制符号不能精确存储,因此以四舍五入的方式存储。因此你的问题。


I'm using C#.

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)
{
----
}

Unfortunately it does not enter the if statement

1) Should I use Double or double???

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.

In short - a float/double can't store 0.1 precisely. It will always be a little off.

You can try using the decimal type which stores numbers in decimal notation. Thus 0.1 will be representable precisely.


You wanted to know the reason:

Float/double are stored as binary fractions, not decimal fractions. To illustrate:

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

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#中的double值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆