+ 1
C++ if statement
Can someone explain why this if statement outputs false? https://code.sololearn.com/cjzZEn39c09H/#cpp
4 ответов
+ 6
It happens that the closest double to 0.2 is larger than the rational number 0.2 but that the closest double to 0.3 is smaller than the rational number 0.3 . The sum of 0.1 and 0.2 winds up being larger than the rational number 0.3 and hence disagreeing with the constant in your code.
-Stack Overflow
Change the double to float which has less precision.
Here is the link:
https://stackoverflow.com/questions/588004/is-floating-point-math-broken
+ 6
Similar questions have been asked before.
https://www.sololearn.com/discuss/2011017/?ref=app
You should understand why 0.1+ 0.2 != 0.3 based on the above link and the answers given before.
The interesting part is: why cout is printing 0.3?
Run this code:
cout << cout.precision();
The reason seems to be that cout rounds the values given to make them match its precision. I am a C++ noob so community feel free to correct me if I'm wrong.
+ 4
Computer calculates in binary format..i.e:-:0.1 which is 1/10 is a repeating fraction it can not be represented in binary pattern..so this type of operations become inaccurate..
+ 2
Thank you all!