C语言的scanf怎么没执行?

#include <stdio.h>
#include <ctype.h>
void main()
{
char answer='N';
double total=0.0;
double value=0.0;
int count=0;

printf("\nThis program calculates the average of"" any number of values");

for(;;)
{
printf("\nEnter a value:");
scanf("%lf",&value);
total+=value;
++count;

printf("Do you want to enter another value?(Y or N):");
scanf("%c",&answer); //没有执行呀
if(tolower(answer)=='n')
break;
}
printf("\nThe average is %.2lf\n",total/count);
}

scanf("%c",&answer);

一般都会停下来让我们输入的!可是有直接跳回去循环了!

这是因为在上一次使用scanf后没有清空输入缓存, 这样你再次使用scanf的时候函数就可能会认为你已经输入过了。

解决这一问题的最简单办法是在接收字符的scanf的控制符"%c"中的%前加一个空格写成" %c",把前一次输入遗留在输入缓冲区里的所有广义空格(' '、'\t'、'\n'等)都吸收掉。

扩展资料:

 函数原型

int scanf(const char * restrict format,...);

函数 scanf() 是从标准输入流stdin(标准输入设备,一般指向键盘)中读内容的通用子程序,可以说明的格式读入多个字符,并保存在对应地址的变量中。

函数的第一个参数是格式字符串,它指定了输入的格式,并按照格式说明符解析输入对应位置的信息并存储于可变参数列表中对应的指针所指位置。

参考资料来源:百度百科-scanf (计算机语言函数)

温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2017-10-07
这种情况通常发生在前面已经有了输入语句,而当前的scanf是在接收字符(即用%c控制输入)时。由于前面的输入语句(不一定是scanf)把最后输入的'\n'遗留在了输入缓冲区,而当前的scanf("%c",...);又会把'\n'当一个字符接收,又由于scanf在%c控制下只接收一个字符,所以就不能接收正式输入的字符了。解决这一问题的最简单办法是在接收字符的scanf的控制符"%c"中的%前加一个空格写成" %c",把前一次输入遗留在输入缓冲区里的所有广义空格(' '、'\t'、'\n'等)都吸收掉。在接收字符的scanf前加getchar()等的办法其实是有漏洞的——当缓冲区里只遗留了一个广义字符时可正常工作,若多于一个则同样出错。
第2个回答  2010-10-26
这是因为你在上一次使用scanf后没有清空输入缓存, 这样你再次使用scanf的时候函数就可能会认为你已经输入过了. 改进的办法很简单, 就是在scanf语句之前使用fflush();函数stdin/stdout

fflush(stdin);//清空输入缓存.

.

改进之后的程序为:

#include <stdio.h>
#include <ctype.h>
void main()
{
char answer='N';
double total=0.0;
double value=0.0;
int count=0;

printf("\nThis program calculates the average of"" any number of values");

for(;;)
{
printf("\nEnter a value:");

fflush(stdin);//清空输入缓存.
scanf("%lf",&value);
total+=value;
++count;

printf("Do you want to enter another value?(Y or N):");

fflush(stdin);//清空输入缓存.
scanf("%c",&answer); //没有执行呀
if(tolower(answer)=='n')
break;
}
printf("\nThe average is %.2lf\n",total/count);
}

//已经调试成功, 希望对你有帮助本回答被提问者采纳
第3个回答  2010-10-26
scanf("%lf",&value);
getchar(); // 清除回车符,避免被下面的"scanf("%c",&answer);"接收
total+=value;
相似回答