Home  >  Article  >  Backend Development  >  How to calculate average in C language

How to calculate average in C language

下次还敢
下次还敢Original
2024-04-13 21:15:14802browse

Average calculation formula: average = sum/number C language implementation: define array to store numbers, define variables to store sum and number, traverse array, calculate sum, calculate average, output average

How to calculate average in C language

C language to find the average

The formula for calculating the average

The formula for the average is : Average = sum/number

C language implementation

The following is a program to calculate the average in C language:

<code class="c">#include <stdio.h>

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    int sum = 0;
    int count = sizeof(numbers) / sizeof(int);
    float average;

    // 计算总和
    for (int i = 0; i < count; i++) {
        sum += numbers[i];
    }

    // 计算平均数
    average = (float)sum / count;

    // 输出平均数
    printf("平均数:%.2f\n", average);

    return 0;
}</code>

Program Description

  • Define an arraynumbers to store a set of numbers.
  • Define variables sum to store the sum, and count to store the number of array elements.
  • Use a for loop to iterate through the array and calculate the sum.
  • Calculate the average and store it in the variable average.
  • Use the printf function to print the average.

The above is the detailed content of How to calculate average in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn