对于循环不太有效

时间:2013-03-10 19:07:02

标签: c++ loops if-statement for-loop

这是我对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;
}

2 个答案:

答案 0 :(得分: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

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

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