我现在正在读Ivor Horton的“从C开始”。不管怎样,我的不确定for
在继续之前会打印我的printf
语句两次。我确信我做错了什么,但我从书中正确地复制了代码。如果重要的话,我会使用Dev-C++。这是代码。谢谢
#include <stdio.h>
#include <ctype.h> // For tolower() function //
int main(void)
{
char answer = 'N';
double total = 0.0; // Total of values entered //
double value = 0.0; // Value entered //
int count = 0;
printf("This 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("The average is %.2lf.", total/count);
return 0;
}
发布于 2013-06-28 11:24:44
如果我们简单地浏览一下您的程序,将会发生以下情况:
scanf
键读取数字,但将换行符留在队列中。它提示用户键入Y或N。
显然,我们需要跳过换行符。幸运的是,这很简单,尽管不明显:在格式字符串的开头添加一个空格,例如:
scanf(" %c", &answer);
格式字符串中的空格表示“在读取下一个内容之前,尽可能多地跳过空格”。对于大多数转换,这是自动完成的,但对于字符串或字符则不是。
发布于 2013-06-28 11:25:00
更改此行
scanf("%c", &answer);
至
scanf(" %c", &answer);
空格将导致scanf忽略您输入的字符之前的空格。
空格是在提供数字后按Enter键的结果。
发布于 2013-06-28 11:41:42
代码很好,唯一遗漏的是在scanf
函数之前的fflush(stdin)
;。它可以总是在scanf
函数之前使用,以避免这些缺陷。按下'Enter‘键会将换行符'\n’作为标准输入缓冲区的输入。因此,循环中的第一个scanf函数假定它是输入,而不是等待用户输入值。
#include <stdio.h>
#include <ctype.h> // For tolower() function //
int main(void)
{
char answer = 'N';
double total = 0.0; // Total of values entered //
double value = 0.0; // Value entered //
int count = 0;
printf("This program calculates the average of"
" any number of values.");
while(1)
{
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("The average is %.2lf.", total/count);
getch();
return 0;
}
如果您使用的是console,还要添加一个getch()
函数来查看结果。
https://stackoverflow.com/questions/17356679
复制相似问题