本文介绍了.1 + .2 = 0.30000000000000004的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,mOnePlusTwo的计算结果为0.30000000000000004(尽管它的b $ b显示为.3)。因此,将该值与mThree(.3)进行比较会导致

为假。


发生了什么?还有什么我应该做的(除了使用小数类型切换到

)?


double mOne = .1;

double mTwo = .2;

double mThree = .3;

double mOnePlusTwo = mOne + mTwo;


bool mEqual = false;

if(mOnePlusTwo == mThree)

{

mEqual = true;

}


Console.WriteLine(" mOne =" + mOne);

Console.WriteLine(" mTwo =" + mTwo);

Console.WriteLine(" mThree =" + mThree);

Console.WriteLine(" mOnePlusTwo =" + mOnePlusTwo);

控制台。 WriteLine(" mThree == mOnePlusTwo?=" + mEqual);

In the below code, mOnePlusTwo evaluates to 0.30000000000000004 (although it
displays as ".3"). Consequently, comparing that value to mThree (.3) results
in false.

What''s going on? Is there something else I should do (other than switch to
using decimal types)?

double mOne = .1;
double mTwo = .2;
double mThree = .3;
double mOnePlusTwo = mOne + mTwo;

bool mEqual = false;
if (mOnePlusTwo == mThree)
{
mEqual = true;
}

Console.WriteLine("mOne = " + mOne);
Console.WriteLine("mTwo = " + mTwo);
Console.WriteLine("mThree = " + mThree);
Console.WriteLine("mOnePlusTwo = " + mOnePlusTwo);
Console.WriteLine("mThree == mOnePlusTwo? = " + mEqual);

推荐答案




切换到小数并阅读这篇文章:



-

Reginald Blue

我一直希望我的电脑和我的电话一样容易使用。我的愿望成真了。我不再知道如何使用我的

电话。

- Bjarne Stroustrup(C ++的创始人)[引自2003年

国际智能用户界面会议]



Switch to decimal and read this article:

What Every Computer Scientist Should Know About Floating-Point Arithmetic
http://docs.sun.com/source/806-3568/ncg_goldberg.html

--
Reginald Blue
"I have always wished that my computer would be as easy to use as my
telephone. My wish has come true. I no longer know how to use my
telephone."
- Bjarne Stroustrup (originator of C++) [quoted at the 2003
International Conference on Intelligent User Interfaces]





这篇关于.1 + .2 = 0.30000000000000004的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 14:49