How to use floating-point number in conditional if-else statement ??? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to use floating-point number in conditional if-else statement ???

#include<stdio.h> int main() { float a=2.5; if(a==2.5) printf("Coding is fun"); else printf("Solo Learn"); return 0; } // Output :- Solo Learn

25th May 2020, 1:59 PM
Ajay Kumar Maurya
Ajay Kumar Maurya - avatar
2 Answers
+ 1
Float values can't be compared like that, because the computer stores them not exactly. For example: 2.5f could be stored like 2.5000001f.
25th May 2020, 2:04 PM
CapCode
+ 1
I think its not the best idea to compare float points with default operators like == or >,<,!=. Write a function for the comparison instead where you send two floats you want to compare and if their diferrence is smaller than a very small number (like 10^-9) then u can say they are equal. This is because a=2.5 and 2.5 may nit have same precision when stored as floating point or double
25th May 2020, 2:56 PM
Asirap