最近我在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),那么比较就会奏效。但我不确定解决方案,请帮忙!非常感激!
可能重复的[我应该如何做浮点比较?](http://stackoverflow.com/questions/4915462/how-should-i-do-floatingpoint-comparison) – Slava 2014-11-04 18:49:45