计算平均值,不包括上次得分

Calculate the average without including last score

本文关键字:不包括 平均值 计算      更新时间:2023-10-16

如果不包括最后一场比赛,我如何计算平均值。我不想包括最后一个游戏,因为它结束了用户需要输入-1的循环。所以,当用户输入-1时,这个游戏被包括在平均值中,而不应该这样结束游戏,而不是实际的分数。有办法绕过这个吗?

while (points != -1) 
{ 
total = total + points;
game++;  
cout << "Enter the points for game " << game << ": ";   
cin >> points; 
average = total / game;
}    
cout << "nThe total points are " << total << endl;
cout << "n The average points are " << average << endl;
system("PAUSE");
return 0;
}

部分基于描述和缺失的代码,很难准确地说出您想要什么。我假设-1表示"停止循环">

以下是我认为您正在寻找的:

game = 0;
total = 0;
while (1) {
++game;
cout << "Enter the points for game " << game << ": ";
cin >> points;
if (points == -1)
break;
total = total + points;
}
game -= 1;
if (game > 0)
average = total / game;
else
average = 0;
cout << "nThe total points are " << total << endl;
cout << "n The average points are " << average << endl;
system("PAUSE");
return 0;

如果是-1,你可以在除以总分和减量之前测试你的分数:

while (points != -1) 
{ 
total = total + points;
game++;  
cout << "Enter the points for game " << game << ": ";   
cin >> points; 
if(points==-1){
game--;}
average = total / game;
}    
cout << "nThe total points are " << total << endl;
cout << "n The average points are " << average << endl;
system("PAUSE");
return 0;
}
while (points != -1) // <--3
{ 
total = total + points;
game++;  
cout << "Enter the points for game " << game << ": "; // <--1 
cin >> points; 
average = total / game; // <--2
}    

我标记了操作顺序。问题是,在检查了"-1"之后,您要添加要求平均值的点。

while (temp != -1)
{
total = total + points;
cout << "Enter the points for game " << game << ": ";
cin >> temp;
if(temp != -1)
{
game++;
points = temp;
average = total / game;
}
}

我添加了一个变量来临时保存要检查的输入值,然后再修改要求平均值的主变量。