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

int main()
{
    {
        float test1Marks, test2Marks, test3Marks, averageMarks;
        averageMarks = (test1Marks + test2Marks + test3Marks) / 3;

        printf("Test 1 Marks:");
        scanf("%f", &test1Marks);

        printf("Test 2 Marks:");
        scanf("%f", &test2Marks);

        printf("Test 3 Marks:");
        scanf("%f", &test3Marks);

        printf("Average Marks of tests are:%f", averageMarks);

    }
    return 0;
}


一切正常,但最终输出给出平均值是错误的。
但是,当我将值分配给两个变量并通过scanf语法输入第三个值时,则无法给出平均值。

最佳答案

averageMarks=(test1Marks+test2Marks+test3Marks)/3;移动到最后一个scanf之后但要打印平均值的print语句之前!

int main()
{
    float test1Marks,test2Marks,test3Marks,averageMarks;

    printf("Test 1 Marks:");
    scanf("%f",&test1Marks);

    printf("Test 2 Marks:");
    scanf("%f",&test2Marks);

    printf("Test 3 Marks:");
    scanf("%f",&test3Marks);

    /* Now with determined test1Marks, test2Marks, and test3Marks
       values we can compute their average:
    */
    averageMarks=(test1Marks+test2Marks+test3Marks)/3;

    printf("Average Marks of tests are:%f",averageMarks);

    return 0;
}

关于c - 这个C程序给出的平均值为零,这有什么问题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45197154/

10-16 08:07