How to calculate the average in the C programming language?

In the C programming language, one can find the average of a set of numbers by following these steps:

  1. Declare a variable called sum to store the total sum of all numbers.
  2. Declare the variable “count” to store the number of items.
  3. Use a looping structure (such as a for loop or while loop) to sequentially read each number and add it to the sum.
  4. Increase count by 1 after each iteration.
  5. After the loop ends, divide sum by count to get the average.
  6. Output the average.

Below is a sample code:

#include <stdio.h>

int main() {
    int n; // 数的个数
    float num, sum = 0, average;

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

    printf("请输入%d个数:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%f", &num);
        sum += num;
    }
    
    average = sum / n;
    printf("平均数为:%.2f\n", average);

    return 0;
}

In this example, the user is required to input the number of values for which the average is to be calculated. Then, the user needs to enter each of these numbers one by one. The program will read each number in sequence and add it to the sum. Finally, the program will calculate the average and output the result.

bannerAds