15 c floating-point
我今天参加了C考试,我被问到类似的问题:
这个程序有什么问题:
Run Code Online (Sandbox Code Playgroud)for( x = .1 ; x != 1.0 ; x += .1) printf("%f\n", x);
我无法解决它,因为我必须写一些我标记.1为错误的东西.但是,当我回到家里时,我运行了这个程序,事实证明它在x等于1.0并陷入无限循环时不会中断:
$ cat exam.c
#include <stdio.h>
int main(int argc, char **argv)
{
float x;
for(x = .1 ; x != 1.0 ; x += .1)
printf("%f\n", x);
return 0;
}
$ gcc exam.c -o exam
$ ./exam
0.100000
0.200000
0.300000
0.400000
0.500000
0.600000
0.700000
0.800000
0.900000
1.000000 <- ?
1.100000
1.200000
1.300000
1.400000
1.500000
....
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么会发生这种情况.
Ani*_*han 18
在循环中使用浮点并非没有问题.舍入误差累积.即使使用<=,循环可能也不会运行正确的次数.
它适用于<=1.0 (10次),但运行时间少于预期<=50.0 (499次).
for(i = 0.1 ; i <= 50.0 ; i += 0.1)
{ ... }//runs 499 times, not 500!
Run Code Online (Sandbox Code Playgroud)
如果遇到这个问题,这个问题可能不容易被发现.在比较之前对其进行舍入(舍入函数)可能有所帮助,但唯一可靠的解决方案是......
在循环中使用整数作为控制变量.
rek*_*ire 17
这是家庭作业的典型问题.
问题是0.1不能精确地存储在浮点数中,检查<= 1.0
然而,这只适用于非常有限的范围,如Cthulhu说.我完全错过了这个问题.因为最好在以后使用int并除以其值.