我正在爲我的課程之一編寫代碼,而且我碰到了一堵牆。我需要用戶輸入一個將被用作for循環重複次數的數字。我要求這個數字的第一個循環是一個while循環。我需要確保輸入的值是一個數字,而不是一個字母或特殊字符。如何確保輸入的值是一個數字?
我不知道如何確保它不是字母或特殊字符。
下一個問題是確保for循環只運行指定的次數,即第一次循環中提供的次數。
這就是我到目前爲止所寫的內容。
#include <stdio.h>
int main()
{
int num_of_scores, n;
char enter;
float score=-1, total=0, average;
do
{
printf("\n\nEnter the number of quiz scores between 1 and 13: ");
scanf ("%d, %c", &num_of_scores, &enter);
}
while(num_of_scores<1 || num_of_scores>13/* && enter == '\n'*/);
printf("\nStill Going!");
for(n=0; n<num_of_scores; n++)
{
printf("\nEnter score %i: ", n+1);
scanf ("%f", &score);
while(score>=0 || score<=100)
{
total = total + score;
score = -1;
break;
}
}
average = total/num_of_scores;
printf("\nThe average score is %.0f.\n\n", average);
return 0;
}
所以我編輯的代碼一點點。在第一個while循環中有一部分位於註釋中,因爲它在該循環之後使程序結束了。 printf(「仍在繼續」)只是一個測試,以確保該程序得到這麼多。任何進一步的指針?我仍然不確定如何檢查確保沒有輸入號碼。我雖然增加了& & enter =='\ n'會做到這一點,但如果它掛起程序,它是不好的。你提出的很多例子都很好,但是我覺得它們有點混亂。謝謝!
你應該使用它之前初始化值設置爲0。 num_of_scores有可能包含垃圾值。 –
約翰我相信我解決了這個問題。我有嗎? – jeaboswell