+ 3

Why does this code shows output false?

https://code.sololearn.com/ck4RVxVmFTm6/?ref=app

18th Apr 2020, 4:56 AM
Dipra Irham
Dipra Irham - avatar
8 Answers
18th Apr 2020, 5:57 AM
Asgar Ali
Asgar Ali - avatar
+ 3
Bro, you need to understand the concept. The values in f1==0.1 are considered to be double precision floating values unless you specify it with 0.1f so the correct code is:- #include <stdio.h> int main() { float f1 = 0.1; if(f1 == 0.1f) printf("True\n"); else printf("False\n"); return 0; }
20th Apr 2020, 6:09 AM
Sneh Chauhan
Sneh Chauhan - avatar
+ 2
It is risky to compare floating point numbers with the == operator, because it is possible that the values should be equal but they are not because of precision errors. A better way to compare floating point numbers is to assume that two numbers are equal if the difference between them is less than Δ, where Δ is a small number. In practice, the numbers can be compared as follows (Δ = 10^(−9) ): if (abs(a-b) < 1e-9) { // a and b are equal } Note that while floating point numbers are inaccurate, integers up to a certain limit can still be represented accurately. For example, using double, it is possible to accurately represent all integers whose absolute value is at most 2^53
18th Apr 2020, 5:12 AM
Arsenic
Arsenic - avatar
+ 2
Thanks Arsenic for the help
18th Apr 2020, 5:16 AM
Dipra Irham
Dipra Irham - avatar
+ 2
Asgar Ali what is meant by 0.1f?
18th Apr 2020, 8:41 AM
Dipra Irham
Dipra Irham - avatar
+ 2
Dipra Irham he is telling the compiler that 0.1 I'd floating point number. By default the compiler consider it to be double so it typecast "f1" to double instead which give rize to precision error(as I have already mentioned in my previous answer)
18th Apr 2020, 8:56 AM
Arsenic
Arsenic - avatar
+ 1
Because that is False
18th Apr 2020, 5:16 AM
Bagtyyar Batyrow
Bagtyyar Batyrow - avatar
+ 1
// Created by Dipra Irham #include <stdio.h> int main() { float f1 = 0.1; if(f1 == 0.1) { printf("True\n");} else{ printf("False\n");} return 0; } Now its correct my dear friend
19th Apr 2020, 2:22 PM
Jayesh Sharma
Jayesh Sharma - avatar