[英]scanf() only reading first input (number)
我無法解釋它,除了scanf()
只讀取第一個值,然后計算基於此。
int main() {
int i, students = 0;
char name[20];
int tests;
float test_score;
int test_sum = 0;
char letter_grade;
double test_average;
printf("Number of students: ");
scanf("%d", &students);
for (i = 0; i < students; i++) {
printf("\nStudent name %d: ", i + 1);
scanf(" %s", &name);
fflush(stdin);
printf("Number of test(s) for %s: ", name);
scanf("%d", &tests);
fflush(stdin);
printf("Enter %d test score(s) for %s: ", tests, name);
if (i < students) {
scanf("%f", &test_score);
test_sum += test_score;
test_average = test_sum / (float)tests;
}
printf("Average test score: %.2f", test_average);
fflush(stdin);
}
return 0;
}
假設我輸入2名學生,第一名學生有2個考試成績,然后輸入45 87.我應該得到66.00,但我得到22.50。 對於第二個學生,我輸入3個測試分數100 55 87,我得到48.33。 Waaayyy下場。
我知道我做錯了什么,但我無法弄清楚,因為我以前有過工作,但循環不會繼續給第二個學生。
您始終需要檢查scanf()
的返回值以查看它讀取的令牌數。 如果無法閱讀,則需要采取糾正措施。
目前尚不清楚為什么每次都需要fflush(stdin)
。
if (i < students) {
scanf("%f", &test_score);
test_sum += test_score;
test_average = test_sum / (float)tests;
}
應該 :
test_sum = 0;
for (int j = 0; j < tests; j++) {
scanf("%f", &test_score);
test_sum += test_score;
}
test_average = test_sum / (float)tests;
發布的代碼包含幾個問題,包括
int
和float
以及double
變量 scanf()
格式字符串不正確 scanf()
調用錯誤 fflush(stdin)
特別列為C標准中的未定義行為 以下提出的代碼修復了上述所有問題,並編譯得很干凈
#include <stdio.h>
#include <stdlib.h> // exit(), EXIT_FAILURE
// prototypes
void flushStdin( void );
int main( void )
{
int numStudents = 0;
char studentName[20];
int numTests;
double test_score;
double test_sum = 0.0;
//char letter_grade;
double test_average;
printf("Number of students: ");
if( 1 != scanf("%d", &numStudents) )
{ // then scanf failed
perror( "scanf for number of students failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
flushStdin();
for (int i = 0; i < numStudents; i++)
{
printf("\nStudent name %d: ", i + 1);
if( 1 != scanf(" %s", studentName) )
{ // then scanf failed
perror( "scanf for student name failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
flushStdin();
printf("Number of test(s) for %s: ", studentName);
if( 1 != scanf("%d", &numTests) )
{ // scanf failed
perror( "scanf for number of tests failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
test_sum = 0.0;
printf("Enter %d test score(s) for %s: ", numTests, studentName);
for( int j=0; j<numTests; j++ )
{
if( 1 != scanf("%lf", &test_score) )
{ // then scanf failed
perror( "scanf for test score failed");
exit( EXIT_FAILURE );
}
// implied else, scanf successful
flushStdin();
test_sum += test_score;
}
test_average = test_sum / numTests;
printf("Average test score: %.2lf", test_average);
}
return 0;
} // end function: main
void flushStdin()
{
int ch;
while( (ch = getchar() ) != EOF && '\n' != ch);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.