简体   繁体   English

为什么我们不能将运算符与浮点数一起使用?

[英]Why we can't use operators with floating point numbers?

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 ). 您需要警惕的是使用带浮点的等于运算符== ,因为结果可能会让您感到惊讶(例如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 . 您不能做的就是检查x==0.1 ,然后除以x-0.1 Since 0.1 isn't exactly representable, you have rounding in a generally unknown direction. 由于0.1不能精确表示,因此您需要沿通常未知的方向四舍五入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM