简体   繁体   中英

Program to calculate the average of unknown set of numbers in C

I'm attempting to write a program to calculate the average of the numbers inputted by the user.

The user can input as many numbers as they'd like until they enter 0, which breaks the [while] loop.

The difficulty I have is I don't know how to tell the program to sum an unknown set of numbers.

I've spent hours trying to figure this out (I'm entirely new to programming). I would be grateful for any help.

#include <stdio.h>

int main() {

    int numberEntered;
    int sum = 0;

    printf("Program to calculate the average of a series of numbers\n\n");
    printf("Please enter the first number. Enter 0 to stop: ");

    scanf("%d", &numberEntered);
    while (numberEntered != 0)
    {
        sum = sum + numberEntered;
        printf("Please enter another number. Enter 0 to stop: ");
        scanf("%d", &numberEntered);
    }
}

You are almost done. Just count the number of elements and divide the sum by count to get the average . Here type-casting is also required, otherwise average of 2 and 3 will give you 2 which is incorrect.

#include <stdio.h>

    int main() {
    int numberEntered;
    int sum = 0;

    printf("Program to calculate the average of a series of numbers\n\n");
    printf("Please enter the first number. Enter 0 to stop: ");
    scanf("%d", &numberEntered);

    int count_number = 0;

    while (numberEntered != 0)
    {
    sum = sum + numberEntered;
    count_number++;
    printf("Please enter another number. Enter 0 to stop: ");
    scanf("%d", &numberEntered);
    }
    if(count_number>0)
       {printf("AVG: %f",((float)sum)/count_number);}

    }

在中断 while 循环后,您可能还希望保持输入的计数,并最终将总和除以该数字。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM