Calculate Average in C: Complete Guide

In C language, you can calculate the average of a set of numbers using the following method:

  1. Declare a variable to store the sum, another variable to store the count, and a third variable to store the average.
  2. Use a loop statement to read each number and add it to the sum.
  3. After the loop ends, add them up and divide by the total number to get the average value.
  4. Output the average.

Here is an example code:

#include <stdio.h>

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

    printf("请输入数字的个数:");
    scanf("%d", &n);

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

    average = sum / n;
    printf("平均值 = %.2f", average);

    return 0;
}

This code will prompt the user to input the number of numbers, then loop through reading each number and adding them to a sum, finally calculating the average and displaying it. It is worth noting that float variables are used here to store the sum and average in order to obtain more accurate results.

bannerAds