![](/img/trans.png)
[英]Calculating average of all user input numbers using while loops in C#
[英]How to make a while loop and calculating the average of all positive numbers?
你好,我需要做一个 while 循环。 该代码将采用所有正数并计算平均值。 如果按下 0,则代码将停止并打印平均值。 看图片链接。 这是一些代码:
int input = 0;
Console.WriteLine("Enter a number: ");
input = int.Parse(Console.ReadLine());
double average = input / 3;
while (input > 0 )
{
Console.WriteLine(input);
input++;
}
if (input == 0)
{
Console.WriteLine($"Average of all positive numbers is: {average:0.00} ");
}
根据我的评论,这里有一个解决方案,它计算输入了多少个正数并使用该数字来除以结果:
double count = 0; // Declared as double so fractional value is not lost when dividing the sum
int sum = 0;
int input = -1; // Arbitrarily non-zero number, will be overwritten each loop
while (input != 0)
{
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
if (input > 0)
{
sum += input;
count++;
}
}
Console.WriteLine($"Average of all positive numbers is: {sum / count:0.00} ");
input
变量的这个初始值是任意的,并允许 while 循环运行(如有关编写 while 循环的问题)。 这可以重写为使用至少运行一次的do...while 循环。 然后input
根本不需要初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.