C++: calculated float does not enter if

Asked

Viewed 55 times

0

Hi, I need help. I’m not getting into the "if" parole with a floating number obtained after an operation. In the code below when I declare the value 0.05 enters the "if", but when I get the 0.05 by subtracting two float does not enter the "if" and I need to operate values to solve my exercise.

#include<iostream>
using namespace std;

int main(){
    
    float v1=2;
    float v2=1.95;

    float diferenca = v1-v2;
    cout << diferenca << endl;
    
    if (diferenca == 0.05){
        
        cout << "entrou"<< endl; // NAO ESTA A ENTRAR !
    }
}

  • A decimal number in the representation float is naturally inaccurate by definition of the form of representation. Do not use equality to compare a float. Preferably test a range of values. In your case something like: if (diferenca <= 0.05){. If precision is required use some decimal representation library, "Bignum C++ library" for example.

  • In fact I believe that for your problem it would be better to consider an error range, for example: if (diferenca >= 04999 && diferenca <= 0.05001){. Or else: if (round(diferenca* 100) == 5){.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.