How to calculate the average value of an array in the C language?
To find the average of an array, you can use a loop to iterate through the array, adding up all the elements, and then divide by the length of the array. Below is an example code written in C language.
#include <stdio.h>
int main() {
int arr[] = {2, 4, 6, 8, 10}; // 示例数组
int n = sizeof(arr) / sizeof(arr[0]); // 数组的长度
int sum = 0;
float average;
for (int i = 0; i < n; i++) {
sum += arr[i]; // 将数组中的元素累加到sum中
}
average = (float)sum / n; // 求平均值
printf("平均值为: %.2f\n", average);
return 0;
}
Running the code above will produce the following output:
平均值为: 6.00
Note that (float)sum / n is used here to convert sum into a float type in order to ensure that the average value obtained includes decimal points. Without this type conversion, dividing an integer by an integer will result in only the integer part, with the decimal part being truncated.