Use the while loop statement to optimize the input of the heights (meters) of 5 people from the keyboard and find their average height (meters).

/*Description
Enter the height (meters) of 5 people from the keyboard and find their average height (meters).

Input description:
In one line, enter 5 heights in a row (range 0.00~2.00), separated by spaces.
Output description:
One line, output the average height, retaining two decimal places*/

#include<stdio.h>
int main()
{
    double a = 0, b = 0, c = 0, d = 0, e = 0, avg = 0;
    scanf("%lf%lf%lf%lf%lf", &a, &b, &c, &d, &e);
    avg = (a + b + c + d + e) / 5;
    printf("%.2lf", avg);
    return 0;
}


 

/*If you enter more than 5 questions, but enter hundreds or thousands of numbers, it will be very troublesome. We will optimize the code*/

#include<stdio.h>
int main()
{
    double a = 0,sum=0;
    int i=0;
    while (i < 5)//i控制循环次数,5个人i就是5,1000个人i就是1000
    {
        scanf_s("%lf", &a);
        sum = sum + a;//每次输入都将输入的数加到一起
        i++;
    }
    printf("%.2lf", sum / 5);
    return 0;
}

Guess you like

Origin blog.csdn.net/wangduduniubi/article/details/128200959