我正在尝试编写一个程序来计算用户输入的数字的平均值。
用户可以输入任意数量的数字,直到输入0,这会中断[while]循环。
我遇到的困难是我不知道如何告诉程序求和一组未知的数字。
我花了数小时试图弄清楚这一点(我是编程的新手)。我将不胜感激。
#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);
}
}
答案 0 :(得分:1)
您快完成了。只需count
个元素的数量和divide
sum
乘count
即可得到average
。这里也需要type-casting
,否则2和3中的average
会给您2,这是不正确的。
#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);}
}
答案 1 :(得分:0)
您可能还希望保持输入计数,并在打破while循环后最后将总和除以该数字。