How to calculate the average in the C language?
The method to find the average is to add a group of numbers together and then divide the total by the number of numbers.
Here is a sample code written in C language for calculating the average of a set of numbers.
#include <stdio.h>
int main() {
int n, i;
float arr[100], sum = 0.0, avg;
printf("请输入数字的个数: ");
scanf("%d", &n);
while (n > 100 || n <= 0) {
printf("错误!数字的个数应该在1到100之间。\n");
printf("请输入数字的个数: ");
scanf("%d", &n);
}
for (i = 0; i < n; ++i) {
printf("%d. 请输入数字: ", i + 1);
scanf("%f", &arr[i]);
sum += arr[i];
}
avg = sum / n;
printf("数字的平均值 = %.2f\n", avg);
return 0;
}
In this sample code, we start by asking the user to input the number of numbers to be added. Then, using a loop, we prompt the user to input each number one by one and add them together. Finally, we divide the sum by the total number of numbers to calculate the average, and then output the result.