C Programming - Anomaly behaviour of while loop for float condition [duplicate]

杀马特。学长 韩版系。学妹 提交于 2019-12-13 09:25:50

问题


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 actually 1.100000000000000088817841970012523233890533447265625
  • (double)(float)1.1 is actually 1.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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!