2014-11-04 127 views
0

最近我在if语句中比较double时遇到了问题。我试图用双倍数来表示整数。作为初学者,我不确定我的代码出了什么问题。比较double错误C++

这是我的代码:

#include <iostream> 

using namespace std; 

int main(){ 
int x=0;//convert double to int 
long double Out;//Result 
long double In=10;//Input double 

//Loop Begin 
while(In>0){ 
x=In;//convert double to int 
Out= (x/In);//Out(test if whole number, will return 1) 

//test for 1 
//////////////// 
if(Out == 1){ 
    cout<<"[Whole Number] "; 
} 
//////////////// 
//test end 

cout<<"In :"<<In<<", "; 
cout<<"X :"<<x<<", "; 
cout<<"Out :"<<Out<<endl; 
In-=0.1;//decrease to finish loop (eventually) 
} 
//Loop End 

cin.get(); 
return 0; 
} 

这项计划将测试和输出的双(中)整数。我意识到double的准确性影响了if语句,因此我无法得到“[Whole Number]”结果。虽然我发现如果我在“if(Out> = 0.9999)”中使用了(0.9999),那么比较就会奏效。但我不确定解决方案,请帮忙!非常感激!

+1

可能重复的[我应该如何做浮点比较?](http://stackoverflow.com/questions/4915462/how-should-i-do-floatingpoint-comparison) – Slava 2014-11-04 18:49:45

回答

0

你的while循环永远不会停止,它的无限循环。你在while循环中没有做任何“In”值,因此它总是大于0,因此是无限循环。

0

你或许应该modf更直接地解决这个问题:

double int_part, frac_part; 

frac_part = std::modf(in, &int_part); 

if (frac_part == 0) { 
    // int_part contains integer value. 
} else { 
    // process the double non-integer floating point value. 
} 
0

您的代码工作完全正常。如果你从10.0中减去0.1,那么由于四舍五入错误,结果可能是而不是整数,并且你的代码完全告诉你。代码没有错,你的期望是错误的。

if (Out >= 0.9999) 

显然不是一个解决方案,因为如果In> = 10000.0,它将始终为真。

0

做到浮点数被计算机转换为二进制表示的方式,它们本质上是不准确的,从而使逻辑比较有些具有挑战性(http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems)。在执行浮点数的这种比较时,通常会使用表示比较中可接受的最大误差的ε常量(http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm)进行比较。在你的情况下,你需要为epsilon选择一个合适的值(比如0.000001)。然后改变你的比较:

if(abs(out - 1) < epsilon){ //Take the difference between out and 1 
    cout<<"[Whole Number]"; //If it is "close enough" print to console 

}

我更多的Java的家伙,但我相信你会需要的#include stdlib.h中利用了ABS()函数。

希望有帮助!