C Code to Calculate Average

Here is an example code in C language for calculating the average:

#include <stdio.h>

int main() {
    int n, i;
    float sum = 0.0, average;

    printf("请输入要计算平均数的整数个数:");
    scanf("%d", &n);

    while (n <= 0) {
        printf("输入的个数必须大于0,请重新输入:");
        scanf("%d", &n);
    }

    for (i = 1; i <= n; ++i) {
        float num;
        printf("请输入第%d个整数:", i);
        scanf("%f", &num);
        sum += num;
    }

    average = sum / n;
    printf("平均数为:%.2f\n", average);

    return 0;
}

This code prompts the user to enter the number of integers to calculate the average, then input each integer one by one, and finally output the average. When entering the number of integers, it will validate the input; if the input is less than or equal to 0, it will require the user to re-enter. The final result will be rounded to two decimal places.

bannerAds