How to calculate the average value of n numbers input in the C language.
To calculate the average of n numbers, first prompt the user to input n numbers, then add them up, and finally divide by n to get the average.
Here’s an example code:
#include <stdio.h>
int main() {
int n, i;
float sum = 0, average;
printf("请输入要求平均值的数字个数:");
scanf("%d", &n);
printf("请输入%d个数字:\n", n);
for (i = 0; i < n; i++) {
float num;
scanf("%f", &num);
sum += num;
}
average = sum / n;
printf("平均值为:%.2f\n", average);
return 0;
}
In the code, first obtain the input n from the user using scanf, then enter a loop where each time the loop runs, it will use scanf to get a number input from the user and add it to the variable sum. After the loop ends, divide sum by n to get the average value, and then print the result.