+ 1
Does anyone know why it prints a?
#include <stdio.h> int main() { float a=0.7; if(0.7>a){ printf("a"); } else{ printf("b"); } return 0; }
7 odpowiedzi
+ 7
Add this to the code for a answer:
if(0.7>a){
printf("a\n");
printf("a= %.9f", a);
}
+ 2
It happens because there is a chance that a variable stores slightly less value of 0.7 due to the limitations of float values
+ 1
Ok, I see, thank you
+ 1
float variable value is 0.7 I.e a=0.7.
0.7 is double constant value and double constant value is greater than float variable value that's why it satisfied the if condition and print a as an output.
For instance:
int main()
{
float a=0.7 ;
double b=0.7;
printf("%.10f %.10lf",a,b);
}
Output :
value of a = 0.699999....
value of b= 0.7000000...
So,double variable value(0.7000...) is greater than float variable value(0.6999...).
I hope I answered your question.
0
You are printing a [printf("a")] not the value of a to print the value of a it should be print("%f" a)
0
You can double instead of float because, the compiler treats 0.7 as a double literal, not a float.
0
Instead of 0.7>a you can do (float)0.7>a. This is because double is bigger than float.
float a=0.7;
if((float)0.7>a){
printf("a");
}
else{
printf("b");
}