如何将运行总计/计数器添加到C#控制台应用程序

时间:2017-10-17 20:32:07

标签: c# visual-studio oop object

我的应用程序正在接受用户输入(保龄球分数)并将其平均化。我要解决的问题是允许用户随时停止的要求。我放置了10个int变量并假设一个不会计算超过10个。我的问题是,如何保持运行总计/计数,这样如果用户只输入2个平均分数,那我只能除以2?谢谢你的帮助。

Console.WriteLine("Please input the score of game 1: ");
g1 = ReadLine();
game1 = int.Parse(g1);
Console.WriteLine("Would you like to add more scores? Press 'n' to continue to averaging, press any other key to continue!");
playagain = ReadLine();
if(playagain =="n")
{
    calculating(); 
}
Console.Clear();

这就是我编写程序的方式。我是否创建了一个变量,并在while语句中指定自己,以声明是否按下任何其他按钮(程序继续到游戏2的另一个用户输入),为变量添加1?

3 个答案:

答案 0 :(得分:1)

使用List<int>集合存储分数,然后

1)除以列表中值的总和除以列表的count属性:

var scores = new List<int>();
int total = 0;

foreach(var score in scores)
{
  total += score;
}

var average = total / scores.Count;

2)使用LINQ的.Average()方法快速获取列表中所有值的平均值:

var scores = new List<int>();
var average = scores.Average();

自然地使用所需的任何数据类型或转换来获得您需要/期望的准确度。

答案 1 :(得分:0)

close(event)

count变量将保持输入数量的总计,game1变量将继续添加得分。

问题更新;

int count = 0; 
while(playagain != "n")
{
    Console.WriteLine("Please input the score of game 1: ");
    g1 = ReadLine();
    game1 += int.Parse(g1);
    count++;
    Console.WriteLine("Would you like to add more scores? Press 'n' to continue to averaging, press any other key to continue!");
    playagain = ReadLine();        
    Console.Clear();
}

答案 2 :(得分:0)

您可以进入列表并使用Sum()和Average()扩展名。要保持aceepting分数,你可以使用while循环

Random Numbers : [6, 12, 17, 24, 25, 26, 40, 43, 44, 45, 50, 51, 62, 65, 72, 75, 77, 91, 93, 98]
Please enter a number 1 through 100: 66
Your number is : 66
72
75
77
91
93
98
72
75
77
91
93
98
Numbers greater than 66 : None