【发布时间】:2016-10-13 04:35:06
【问题描述】:
只是在 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;
谢谢...
打包机
【问题讨论】:
-
您已经声明了一个名为 dNumSum 的变量。您认为应该如何处理它?
-
请记住,平均值是所有输入的总和除以输入的数量。
-
继 Joachim 的评论之后 - 您可以在用户输入数字时保持输入数字的总和,然后除以任意点的数字计数以显示运行平均值
-
您应该始终检查来自
scanf的返回值。在您的代码中,对scanf的每个调用都应返回 1,因此您需要确保它们确实返回 1。要了解原因,只需键入任意字母,然后按 Enter 键。 -
我知道如何平均一个数字的总和......我无法理解的是用户重复地为同一个变量输入不同的值。当输入每个新数字时,我如何能够保持总和的运行记录?