【问题标题】:The input that i give to my %f does not save我给我的 %f 的输入没有保存
【发布时间】:2021-06-14 14:59:09
【问题描述】:

gradeOne 和 secondGrade 不保存我给出的数字。所以我不能得到平均值,因为总是以 (0 + 0)/2 的除法结束,有人可以帮我吗?

    #include <stdio.h>
    #include <stdlib.h>

    int main()
    {
    int students;
    char name[50];
    double gradeOne, secondGrade, classAverage = 0, average = 0;

    for(students = 1;students <= 15; students++){
        printf("Tell me Your name: \n");
        fflush(stdin);
        scanf("%[^\n]s", &name);
        //saves name
        printf("Tell me your first grade: \n");
        scanf("%f", &gradeOne);
        printf("Tell me your second grade: \n");
        scanf("%f", &secondGrade);
        //saves grade


        printf("\n========================================\n");

        printf("Student: %s\n", name);
        printf("First Grade: %3.2f \nSecond Grade: %3.2f \n", gradeOne, secondGrade);
        printf("%f", average);

        printf("\n========================================\n");

        average = (gradeOne + secondGrade)/2;
        //creates average
        printf("Average of the %d student: %3.2f",students, average);

        classAverage += average;
        //creates class average

    }
        classAverage = classAverage / (students - 1);
        printf("The class average was: %3.2f", classAverage);

    return 0;
}

【问题讨论】:

  • fflush(stdin); 的行为未定义。一旦您的程序表现出未定义的行为,就没有进一步分析的意义。
  • scanf("%[^\n]s", &amp;name) 不正确。几乎可以肯定您打算使用"%[^\n]"。使用尾随 s,如果输入的下一行以 s 开头,它将被匹配并被此消耗。
  • 我建议" %[^\n]",应该是name,而不是&amp;name
  • 使用scanf(" %49[^\n]", name),否则还不如使用邪恶的gets()
  • @WilliamPursell “如果输入的下一行以 s 开头,则在尾随 s”是不对的。 "%[^\n]" 消耗任何 's' 的输入。 "%[^\n]s" 中的 "s" 是多余的。

标签: c math average


【解决方案1】:

%f in scanf() 用于阅读float。您应该使用%lf 阅读double

请注意,您应该在printf() 中使用%f 进行打印 double。较新的规范允许%lf 用于printf(),但%f 应该更好地兼容。

【讨论】:

  • 这也值得一提:scanf("%[^\n]s", &amp;name);
  • @TedLyngmo 还有fflush(stdin);
  • 是的,我没看到那个。有趣:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-30
  • 1970-01-01
  • 1970-01-01
  • 2017-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多