+ 1
need some help with this cpp challenge question
the code snippet goes like this: float f = 0.1; if ( f == 0.1 ) cout<<"True"; else cout<<"False"; it really confused me when i was told that the output is: False i cross checked it with another compiler, only to get the same result. any suggestions welcome. thanks.
2 Antworten
+ 8
#include <iostream>
#include <typeinfo>
using namespace std;
int main() {
float f = 0.1;
cout << typeid(f).name() << endl;
cout << typeid(0.1).name() << endl;
return 0;
}
+ 4
float f = 0.1 is double type value but since it is assigned to a float type variable, there is loss in precision but any floating point number by default is a double.
So f is a float now and 0.1 is a double so they are not equal because as you have guessed by now, there is a change in precision.