請教一下,下面的代碼是哪里錯了,得不到正確的結果,表現不讓輸入Y或N,并直接進入第13行了。主要問題在第18至22行,除錯水平不行沒發現什么問題,但就是不能正確執行這行,致使無法正確判斷輸入的字母與下行‘n’的真偽。如何解決?

#include <stdio.h>
#include <ctype.h>
#include <conio.h>
int main(void)
{
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("\n Enter a value:");
scanf("%lf", &value);
total += value;
++count;
printf("\n Do you want to enter another value?(Y or N):");
scanf("%c", &answer);
if(tolower(answer) == 'n')
break;
}
printf("\nthe average is %.0lf\n", total / count);
_getch();
return 0;
}
uj5u.com熱心網友回復:
for( ; ; )
{
printf("\n Enter a value:");
scanf("%lf", &value);
total += value;
++count;
printf("\n Do you want to enter another value?(Y or N):");
getchar();
scanf("%c", &answer);
if(tolower(answer) == 'n')
break;
}
加一個getchar(),大概原因是第一個scanf存在換行符,恰好用在了第二個scanf上,先用getchar()把換行符吸收了,就可以了
uj5u.com熱心網友回復:
scanf("%c", &answer);這條陳述句前加一個getchar();吧
因為這條陳述句是%c,正好匹配輸入快取里的'\n'。這個'\n'是上一個輸入留下的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/125673.html
標籤:C語言
上一篇:指標與陣列
