【问题标题】:C++ Looping through an Array to display contentsC ++循环遍历数组以显示内容
【发布时间】:2020-12-13 03:53:39
【问题描述】:

我正在编写一个循环来遍历一个 3d 数组并显示 [0][0][0] 到 [0][2][4] 的内容。它从 [0][0][0] 到 [0][0][4] 显示并正常运行,但之后它跳转到 [0][2][0] 而不是 [0][1] [0]。如果有人能纠正我的错误,我不知道为什么是我自己。

a、b、c、d 和 e 都是整数变量。 在这个循环的开始,我将 b 初始化为 0,c 初始化为 1,d 初始化为 0,e 初始化为 1。

for (int a = 0; a < students;)
 {
   cout << "Let's help Student #" << e << "!" << endl;
   do 
    {
     cout << "Question #" << c << ":" << endl;
     cout << math_rooms[0][a][b] << endl;
     cin >> math_rooms[0][a][b];
     cout << " " << endl;
     
     if (math_rooms[0][a][b] != math_answers[0][a][b])
      {       
       d++;
       //Set up the error variable so we keep track of pass/fail
       cout << "Sorry, that was incorrect." << endl;
       cin >> math_rooms[0][a][b];
       cout << " " << endl;
      }
     else
      {
       cout << "That's correct!" << endl;
       cout << " " << endl;
      }
         
     //Increment b and c to go through all questions/keep track of question #.
     b++, c++;

     //Set up loop that checks pass_fail on final question.
     if (d >= 3)
      {
       cout << "Sorry, you failed the test." << endl;
       pass_fail = false;
       return pass_fail;
      }

    } while (b < questions);

  //restart counter
  c = 1;
  //Increment a so that it changes to the next student & f so that it keeps track of the student #.
  a++, e++;
 }

所以本质上,循环工作正常,直到它增加 a 变量。它从 0 开始,然后当它应该增加到 1 时,它改为 2。 IDK 为什么?

【问题讨论】:

  • 你在哪里重置b = 0;

标签: c++ arrays nested-loops increment


【解决方案1】:

每次执行for循环都需要重新设置b的值

【讨论】:

  • 非常感谢!意识到这件事是如此简单以至于我一直忽略,这让我很恼火。
猜你喜欢
  • 2021-02-21
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
相关资源
最近更新 更多