-1

I am initializing a variable a of type float with value 1.2.

If I print it on screen, it give me 1.2, but when I check it with if/else, it does not run the if statement whose condition is if(a == 1.2). Instead it runs the else part.

Can someone please help, I am still learning the basics.

Here is my code:

#include<iostream>
#include<iomanip>
using namespace std;

int main ()
{
    float a = 1.2;
    cout<<fixed<<setprecision(1)<<a<<endl;
    
    if (a == 1.2)
        cout<<"\n a is 1.2";
    else
        cout<<"\n a is not 1.2";
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Try if (a == 1.2f) instead of if (a == 1.2) That is use a constant of the type float instead of the type double. – Vlad from Moscow Nov 02 '22 at 18:05
  • `1.2` is a `double`, not a `float`. When you do `a == 1.2` it converts the value held by `a` to a `double` for the comparison. However a float can't store as precise a representation of `1.2` as double so the value you get when you convert back to `double` is slightly different from the original `1.2` double value. – François Andrieux Nov 02 '22 at 18:05
  • 1
    Read this in its entirety https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – possum Nov 02 '22 at 18:07
  • 2
    Another good read: [Is floating point math broken?](https://stackoverflow.com/q/588004/3282436) – 0x5453 Nov 02 '22 at 18:10
  • Floating point numbers are *not* exact (in general). – Jesper Juhl Nov 02 '22 at 18:20
  • 1
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Richard Critten Nov 02 '22 at 18:23
  • [Why are floating point numbers inaccurate?](https://stackoverflow.com/questions/21895756/) – Remy Lebeau Nov 02 '22 at 19:18

1 Answers1

0

The it-statement is comparing a float to a double. 1.2 is a double and not a float.

Maybe this will give you some clarity: Why comparing double and float leads to unexpected result?

Hope this helps!