这一小段代码为什么会出现死循环。。。

avatar 140992
bryanjhy
1697
4
#include

int main (void)
{
float a;
float c=1;
while(scanf("%f", &a)!=1)
{
printf("This is not a number.\n");
printf("Please enter another number.\n");

}
return 0;
}
这是在vc++6.0跑的一段c语言代码,目的是为了确保用户最终输入浮点数,并将值赋给a,本来打算是如果输入一个‘k’,再按一下回车,就会出现那两行语句,并可以重新输入,但是结果却是个死循环。。。这是为神马,
#include

int main (void)
{
float a;
float c=1;
while(scanf("%f", &a)!=1)
{
printf("This is not a number.\n");
printf("Please enter another number.\n");
while(getchar()!='\n');

}
return 0;
}
我加了其中一句就没有这种问题了,但是不知道为什么。。。是scanf的机制问题么。。。。我是编程新手。。。

补充内容 (2015-1-25 21:51):
下面那段那个“float c=1”可以无视。。。。
4条回复