need some help with this cpp challenge question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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.

23rd Nov 2020, 5:26 AM
Priyansh Agrahari
Priyansh Agrahari - avatar
2 Answers
+ 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; }
23rd Nov 2020, 5:48 AM
Mariano Fregosi
Mariano Fregosi - avatar
+ 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.
23rd Nov 2020, 5:40 AM
Avinesh
Avinesh - avatar