将更改的数字分配给单个变量

时间:2016-10-13 04:35:07

标签: c math average

只是在C中搞砸...想要制作一个程序来计算用户输入的任何数字的平均值。

该程序运行正常,我只是不能逻辑'如何做下一部分。

我需要能够输入他们输入的每个数字并使用他们为第一个scanf输入的数字进行平均。我只为他们输入的每个数字分配了一个变量,但是经过大约一秒钟查看代码我意识到我需要使用微积分或一些编程技巧才能(有效地)无限地执行此操作。基本上,变量需要每次都改变,以便可以取总和然后除以总数。我咆哮......

任何能理解我愚蠢问题的人能给我一些指示吗?那太棒了......

我的包含和int main()在那里,不用担心。只是觉得没有必要用已知的东西弄乱它。另外,我不做任何简写 - 我觉得现在没必要。

// Base variables
int iUserReq, iNumCounter = 0;
// Each individual number
double dUserNum = 0.0;
// Calculation
double dNumSum = 0.0, dNumAvg = 0.0;


// Ask user for the number of variables to be averaged... will come in handy
printf("Please input how many numbers you would like to average together, as a number. For example, 10.\nTry to keep it low, because you're going to be putting them all in manually.   >   ");
scanf("%d", &iUserReq);

// If user inputs 0 or negative number, keep asking until they put in a positive number
while(iUserReq <= 0)
{
    printf("Please input a number greater than 0.   >   ");
    scanf("%d", &iUserReq);
}

// This adds a counter, so for the number of numbers the user wants to average, it will loop that many times and ask for an input that many times
// I.e. they want to average 10 numbers, it asks for 10 numbers

// THIS IS WHERE I'M STUCK... HELP?
while(iNumCounter < iUserReq)
{
    printf("Please input number.   >   ");
    scanf("%lf", &dUserNum);
    iNumCounter = iNumCounter + 1;
}

return 0;

谢谢...

巴格

1 个答案:

答案 0 :(得分:0)

好的,我要咬一口给你解决方案。

在您的计划的顶部:

double sum = 0.0;

每个数字的scanf()之后:

sum += dUserNum;

return 0

之前
printf("%f\n", sum / iUserReq);

你明白为什么会这样吗?