【问题标题】:scanf() only reading first input (number)scanf() 只读取第一个输入(数字)
【发布时间】:2016-08-16 18:44:20
【问题描述】:

除了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。对于第二个学生,我输入 100 55 87 的 3 个测试分数,我得到 48.33。哇哦。

我知道我做错了什么,但我想不通,因为我之前有它工作过,但循环不会继续到第二个学生。

【问题讨论】:

  • 你知道fflush(stdin)是做什么的吗?
  • if (i &lt; students) { --> for(int j = 0; j test_sum)。
  • @EOF 清除缓冲区。当我不包含它时,我的程序就结束了。我确实看到它有多么多余,但我不知道为什么我的代码没有它们就无法忍受。
  • @BLUEPIXY 试过了,但我得到了缺少 } 和 ) 之类的错误,这真的很奇怪。
  • @DSmith:在标准、可移植的 C 语言中,fflush(stdin) 是未定义的行为。 POSIX 和 windows 为它定义了行为,但我不知道它在任何情况下都有用。

标签: c scanf


【解决方案1】:
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;

【讨论】:

  • 这似乎是获得正确计算的唯一方法,但我的程序在此之后立即结束并且它没有到达学生 #2。我还删除了 fflush(stdin)。我已经转了几个小时了......
  • test_sum 变量应该在 for 循环之前设置为 0
【解决方案2】:

您总是需要检查scanf() 的返回值以查看它读取了多少令牌。如果无法读取,您需要采取纠正措施。

不清楚为什么每次都需要fflush(stdin)

【讨论】:

    【解决方案3】:

    发布的代码包含几个问题,包括

    1. 只能输入一个考试成绩
    2. intfloatdouble 变量的随机混合
    3. 调用scanf() 的格式字符串不正确
    4. 许多未使用的变量
    5. 未能检查调用scanf() 的错误
    6. 变量命名不佳。变量名称应指示内容或用法(或两者都更好)
    7. 调用 fflush(stdin) 在 C 标准中被明确列为未定义行为
    8. test_sum 未在学生之间重新初始化

    以下建议的代码修复了上述所有问题并编译干净

    #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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多