1

这是我第一次尝试 for 循环,我遇到了一些问题。我正在尝试编写一个程序,询问两支球队每节得分多少,然后显示总分和获胜球队。

#include <iostream>

using namespace std;

int main( )
{
    int scoreA = 0;
    int scoreB = 0;

    cout << "This program calculates the average score of 10 tests." << endl;

    for (int counter = 0; counter < 4; counter = counter + 1)
    {
        cout << "Enter Team A's quarterly points: ";
        cin >> scoreA;
        cout << "Enter Team B's quarterly points: ";
        cin >> scoreB;
        scoreA = scoreA + scoreA;
        scoreB = scoreB + scoreB;
    }

    cout << "Team A's Score: " << scoreA << endl;
    cout << "Team B's Score: " << scoreB << endl;
    if (scoreA > scoreB)
    {
               cout << "Team A wins";
               }
    else
    {
        cout << "Team B wins";
        }

    system("pause");
    return 0;
}
4

2 回答 2

1

您存储分数总和的变量和您从用户输入的变量应该不同。喜欢(阅读评论):

int sumB=0 , sumB=0; // added this 
for (int counter = 0; counter < 4; counter = counter + 1){
  cout << "Enter Team A's quarterly points: ";
  cin >> scoreA;
  cout << "Enter Team B's quarterly points: ";
  cin >> scoreB;
  sumA = sumA + scoreA;
  sumB = sumB + scoreB;
  //  ^      ^
}

例如,在您的代码中,您正在做类似的事情,scoreA = scoreA + scoreA;并且cin >> scoreA 两个语句在循环期间都覆盖了彼此的影响,并且同样发生在scoreB.

因此也相应地更改代码中的下一行,例如:

cout << "Team A's Score: " << sumA << endl;
cout << "Team B's Score: " << sumB << endl;
if (sumA > sumB){
  // your code
}
else{
 // your code
}

此外,由于您是 c++ 和 SO 的新手,我想建议一个链接:The Definitive C++ Book Guide and List

于 2013-03-10T19:11:21.350 回答
1

您并没有具体说明循环不起作用,但我在您的 for 循环中看到以下内容:

cout << "Enter Team A's quarterly points: ";
cin >> scoreA;
cout << "Enter Team B's quarterly points: ";
cin >> scoreB;
scoreA = scoreA + scoreA;
scoreB = scoreB + scoreB;

因此,您将在每次迭代 () 中覆盖 scoreA 和 scoreB 中的分数cin >> scoreA,然后将它们加倍 ( scoreA = scoreA + scoreA)。

于 2013-03-10T19:12:00.837 回答