Please explain why the following pieces of code behave differently.
#include<stdio.h>
int main(){
float a=0.1;
if(a<0.1)
printf("less");
else
printf("greater than equal");
getchar();
}
Output:greater than equal
#include<stdio.h>
int main(){
float a=0.7;
if(a<0.7)
printf("less");
else
printf("greater than equal");
getchar();
}
Output:less contrary to what i expected.
PS: This is NOT homework.
You cannot use comparison operators on floating point numbers reliably.
A good way of comparing two floating point numbers is to have a accuracy threshold which is relative to the magnitude of the two floating point numbers being compared.
Something like:
Good Read: