怎么比较双? [英] How to compare double?

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

问题描述

当x等于1时,下一个代码不显示消息Equal:

The next code doesn't show the message "Equal" when x is equal 1:

for (double x = 0; x <= Convert.ToDouble(1); x += 0.1)
{
    MessageBox.Show(x.ToString());
    if (x == Convert.ToDouble(1)) MessageBox.Show("Equal");
}



如何解决?


How to fix?

推荐答案

强制性链接:每个计算机科学家应该知道的关于浮点运算的内容 [ ^ ]。


在您阅读Carlo发布的文章后 - 了解浮点问题...

使用十进制 [ ^ ] ...

After you read the article Carlo posted - and understood the floating point problem...
Use Decimal[^]...
for ( decimal x = 0; x <= ( decimal )1; x += ( decimal )0.1 )
{
    Debug.WriteLine ( x.ToString ( ) );
    if ( x == ( decimal )1 )
        Debug.WriteLine ( "Equal" );
}


这篇关于怎么比较双?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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