+ 1

Why output is different

main() { float x=7.75; if(x==7.75) printf("I am right"); else printf("I am wrong'); } Output : I am right main() { float x=0.075; if(x==0.075) printf("I am right"); else printf("I am wrong'); } Output : I am wrong Note:- If we use double instead of float output is always I am right. So why it's not possible in float.

25th Aug 2016, 4:56 PM
Aayush Rawat
Aayush Rawat - avatar
1 Réponse
+ 1
Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine. The problem is easier to understand at first in base 10. Consider the fraction 1/3. You can approximate that as a base 10 fraction: 0.3 or, better, 0.33 or, better, 0.333 and so on. No matter how many digits you’re willing to write down, the result will never be exactly 1/3, but will be an increasingly better approximation of 1/3. It's actually quite interesting to read more about this, because all programmers will have to face the importance of choosing your correct data types some time. //I got this from python docs
25th Aug 2016, 10:31 PM
Twan Schoenmakers
Twan Schoenmakers - avatar