What's wrong to use operators while you are using floating point numbers. Can't we use '==' '<=' etc operators with floating point numbers?
here is the code.
# include <iostream>
using namespace std;
main(){
float x, y, z;
cout<<"1st integer: ";
cin>>x;
do {
cout<<"2nd integer: ";
cin>>y;
if(y<=0 ){
cout<<"You can't divide by zero"<<endl;
continue;
} else {
break;
}
} while (1);
z = x/y;
cout<<"Result: "<<z;
}
it generate right result as i want to get. But from some where i heard that's not a good logic to use operators with floating point numbers. why?
What you're doing is fine. What you do need to be wary of is using the equality operator ==
with floating point, because the results may surprise you (eg 0.1 + 0.2 != 0.3
).
But there's no problem with using >
, >=
, <=
, <
.
You can compare floating point numbers safely against precisely zero. This will prevent a division by zero.
What you can't do is check x==0.1
and then divide by x-0.1
. Since 0.1 isn't exactly representable, you have rounding in a generally unknown direction.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.