-1

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

3 回答 3

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;
于 2018-10-30T22:40:43.963 回答
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;
    }
}

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

于 2018-10-30T22:38:13.517 回答
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;
}
于 2018-10-30T22:27:32.800 回答