计算平均值,不包括最后得分

时间:2018-10-30 22:23:33

标签: c++ while-loop

如何在不包括上一场比赛的情况下计算平均值。我不想包含最后一个游戏来结束用户需要输入-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;
}

3 个答案:

答案 0 :(得分:1)

要准确地说出您想要什么有点困难,部分原因是基于描述和缺少的代码。我假设-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 :(得分:0)

如果将总和减为-1,您可以先测试点,然后将其除以-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;
}

答案 2 :(得分: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;
    }
}

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

相关问题