为什么"对于(I = 0.1; I = 1.0;!I + = 0.1)"在I = 1.0不破? [英] Why "for( i = 0.1 ; i != 1.0 ; i += 0.1)" doesn't break at i = 1.0?
问题描述
我今天考试了C和有人问我类似的问题:
什么是错的这个计划:
为(X = 0.1; X = 1.0;!X + = 0.1)
的printf(%F \\ N,X);
块引用>我不解决这个问题,因为我不得不写东西,我打上
.1
为错误。但是,当我回到家里,我运行这个程序,原来,当X
等于1.0 $ C它不会破坏$ C>,并停留在一个无限循环:
$猫exam.c
#包括LT&;&stdio.h中GT;INT主(INT ARGC,字符** argv的)
{
浮X; 为(X = .1; X = 1.0;!X + = 0.1)
的printf(%F \\ N,X); 返回0;
}
$ GCC exam.c -o考试
$ ./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
....可能有人请解释为什么发生这种情况。
解决方案这是功课典型的问题。
存在的问题是,0.1不能精确存储在一个浮更好检查&下; = 1.0
然而这仅仅只适用范围非常有限像邪神说。我完全错过了这个问题。原因这是更好地使用
INT
后来划分其值I had an exam today in C and I was asked a question similar to:
What is wrong with this program:
for( x = .1 ; x != 1.0 ; x += .1) printf("%f\n", x);
I couldn't solve it and since I had to write something I marked
.1
as an error. But, when I went back home, I run this program, It turned out that it doesn't break whenx
equals to1.0
and stuck in an infinite loop:$ 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 ....
Could someone please explain why this is happening.
解决方案This is a typical question for homework.
The Problem is that the 0.1 cannot be exactly stored in a float better check for <= 1.0
However this just works only for a very limited range like Cthulhu said. I missed that problem completely. Of cause it is better to use
int
and divide its value later.这篇关于为什么&QUOT;对于(I = 0.1; I = 1.0;!I + = 0.1)&QUOT;在I = 1.0不破?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!