首页 > 解决方案 > C ++循环遍历数组以显示内容

问题描述

我正在编写一个循环来遍历 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 为什么?

标签: c++arraysnested-loopsincrement

解决方案


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


推荐阅读