C编程-浮动条件时while循环的异常行为 [英] C Programming - Anomaly behaviour of while loop for float condition
问题描述
我编写了以下代码:
#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;
}
我得到了预期的输出.
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?
更新:只是想出了解决此错误的方法.
附加了while条件,如下所示:while (x == 1.1f)
UPDTATE: Just figured out how to correct this error.
Appended the while condition like this: while (x == 1.1f)
推荐答案
1.1
不是float
值,而是double
值.
编写float x = 1.1;
时,编译器将插入一个隐式强制转换:float x = (float)1.1;
.
When you write float x = 1.1;
the compiler inserts an implicit cast: float x = (float)1.1;
.
编写x == 1.1
时,编译器将插入另一个隐式强制转换:(double)x == 1.1
.
When you write x == 1.1
the compiler inserts another implicit cast: (double)x == 1.1
.
因此,有效地测试了将1.1强制转换为float
并返回到double
后1.1值是否仍然相同-即(double)(float)1.1 == 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
不正确.至少在我的平台上:
(double)(float)1.1 == 1.1
is not true, due to floating-point rounding error. At least on my platform:
-
1.1
实际上是1.100000000000000088817841970012523233890533447265625
-
(double)(float)1.1
实际上是1.10000002384185791015625
1.1
is actually1.100000000000000088817841970012523233890533447265625
(double)(float)1.1
is actually1.10000002384185791015625
并且您会看到这两个数字不相同.
and as you can see these two numbers are not the same.
这篇关于C编程-浮动条件时while循环的异常行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!