我正在读Ivor Horton的Beginning 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;
}
Run Code Online (Sandbox Code Playgroud)
如果我们简要介绍一下您的程序,接下来会发生什么:
scanf 读取数字,但将换行符留在队列中.显然,我们需要跳过换行符.幸运的是,这很容易,如果不明显:在格式字符串的开头添加一个空格,例如:
scanf(" %c", &answer);
Run Code Online (Sandbox Code Playgroud)
格式字符串中的空格意味着"在阅读下一个内容之前尽可能多地跳过空格".对于大多数转换,这是自动完成的,但对于字符串或字符则不会.