Please explain why the following pieces of code behave differently.
#include
int main(){
float a=0.1;
if(a<0.1)
printf(\"less\");
else
#include
int main() {
float a = 0.7;
if (a < 0.7)
printf("less");
else
printf("greater than equal");
getchar();
}
Unsuffixed floating constants are of type double not float. For example, 0.7 is a floating constant of type double.
if (a < 0.7)
As the right operand in the comparison expression is of type double, the usual arithmetic conversion apply and the a value is promoted to double. double and float don't have the same precision. In your case to get the correct result you should have used a floating constant of type float.
if (a < 0.7f)
0.7f is a floating constant of type float.