【水文】求数组的极值、平均值和方差

代码:

#include 
#include 

void calculateStatistics(int arr[], int size) {
    int i;
    double sum = 0.0, mean, variance;
    int max_val = arr[0];
    int min_val = arr[0];

    // 计算最大值和最小值
    for (i = 1; i < size; i++) {
        if (arr[i] > max_val) {
            max_val = arr[i];
        }
        if (arr[i] < min_val) {
            min_val = arr[i];
        }
    }

    // 计算平均值
    for (i = 0; i < size; i++) {
        sum += arr[i];
    }
    mean = sum / size;

    // 计算方差
    sum = 0.0;
    for (i = 0; i < size; i++) {
        sum += pow(arr[i] - mean, 2);
    }
    variance = sum / size;

    printf("最大值:%d\n", max_val);
    printf("最小值:%d\n", min_val);
    printf("平均值:%lf\n", mean);
    printf("方差:%lf\n", variance);
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);

    calculateStatistics(arr, size);

    return 0;
}

你可能感兴趣的:(C)