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

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

问题描述

我有一个名为 xdouble 变量.在代码中,x 被分配了一个 0.1 的值,我在比较 x0.1<的if"语句中检查它/代码>

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语句

  1. 我应该使用 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.

简而言之——float/double 不能精确地存储 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 * 101 + 2 * 100 + 3 * 10-1 + 4 * 10-2

计算机以相同的方式存储浮点数,不同之处在于它使用基数2:10.01表示

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

现在,您可能知道有些数字无法用我们的十进制表示法完全表示.例如,十进制的1/30.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# 中的双精度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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