How to calculate the average value of a one-dimensional array in the C language?

To calculate the average of a one-dimensional array, first compute the sum of all elements in the array, then divide by the length of the array. Using a loop to iterate through the array, accumulate all elements, and finally divide by the array’s length.

Here is a sample code:

#include <stdio.h>

int main() {
    int arr[] = {3, 5, 7, 9, 11};
    int length = sizeof(arr) / sizeof(arr[0]);  // 数组长度
    int sum = 0;  // 总和
    float average;  // 平均值

    // 求和
    for (int i = 0; i < length; i++) {
        sum += arr[i];
    }

    // 求平均值
    average = (float)sum / length;

    printf("数组的平均值为: %.2f\n", average);

    return 0;
}

The above code will produce:

数组的平均值为: 7.00

Please note that in order to get an accurate floating point result, the sum needs to be forcefully converted to float type before dividing it by the length of the array.

bannerAds