【问题标题】:For loop not quite workingFor循环不太好用
【发布时间】:2013-03-10 19:07:01
【问题描述】:

这是我第一次尝试 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;
}

【问题讨论】:

  • 你应该写出问题所在。

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


【解决方案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 &gt;&gt; scoreA) 时都会覆盖 scoreA 和 scoreB 中的分数,然后将它们加倍 (scoreA = scoreA + scoreA)。

【讨论】:

    【解决方案2】:

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

    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 &gt;&gt; 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

    【讨论】:

    • 或者最好是sumA += scoreA
    • @Jite 是的,最好使用+= :)
    • @user2040308 好!!..现在你可能喜欢accept one answer
    猜你喜欢
    • 2018-12-18
    • 2016-01-01
    • 2020-09-09
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    相关资源
    最近更新 更多