问题
I wrote the following code:
#include <stdio.h>
int main ()
{
float x = 1.1;
printf("%s\n", "Hello!");
while (x == 1.1)
{
printf("%s\n", "Hey there!");
printf("%f\n", x);
x = x - 0.1;
}
printf("%s\n", "Bye!");
return 0;
}
However the output was (which I assume was not expected):
aps120797@XENON-PC:/mnt/d/Codes/LetUsC$ gcc C04Ag.c
aps120797@XENON-PC:/mnt/d/Codes/LetUsC$ ./a.out
Hello!
Bye!
To check if it accepts float condition or not, I wrote this code:
#include <stdio.h>
int main ()
{
float x = 1.1;
printf("%s\n", "Hello!");
while (x >= 1.0)
{
printf("%s\n", "Hey there!");
printf("%f\n", x);
x = x - 0.1;
}
printf("%s\n", "Bye!");
return 0;
}
And I got the output as I expected.
aps120797@XENON-PC:/mnt/d/Codes/LetUsC$ gcc C04Ag.c
aps120797@XENON-PC:/mnt/d/Codes/LetUsC$ ./a.out
Hello!
Hey there!
1.100000
Hey there!
1.000000
Bye!
So, my question is, what am I doing wrong in the first code?
UPDTATE: Just figured out how to correct this error.
Appended the while condition like this: while (x == 1.1f)
回答1:
1.1
is not a float
value, it's a double
value.
When you write float x = 1.1;
the compiler inserts an implicit cast: float x = (float)1.1;
.
When you write x == 1.1
the compiler inserts another implicit cast: (double)x == 1.1
.
So effectively you are testing whether 1.1 is still the same value after casting it to float
and back to double
- i.e. whether (double)(float)1.1 == 1.1
is true.
(double)(float)1.1 == 1.1
is not true, due to floating-point rounding error. At least on my platform:
1.1
is actually1.100000000000000088817841970012523233890533447265625
(double)(float)1.1
is actually1.10000002384185791015625
and as you can see these two numbers are not the same.
来源:https://stackoverflow.com/questions/41540392/c-programming-anomaly-behaviour-of-while-loop-for-float-condition