【问题标题】:Nested do-while loop inside a while loop在while循环内嵌套do-while循环
【发布时间】:2020-09-21 14:15:29
【问题描述】:

开始学习 C++ 并遇到任务问题。 该任务要求我将嵌套的 for 循环重写为 while 循环内的 do-while 循环。输出非常不同,所以我认为我做错了什么。 嵌套的 for 循环:

  #include <stdio.h>

  main()
  {
     int i, j;
     for (i=1; i<=3; i++) {   /* outer loop */
         printf("The start of iteration %d of the outer loop.\n", i);
         for (j=1; j<=4; j++)  /* inner loop */
         printf("Iteration %d of the inner loop.\n", j);
     printf("The end of iteration %d of the outer loop.\n", i);
    }
    return 0;
 }

输出:

The start of iteration 1 of the outer loop.
    Iteration 1 of the inner loop.
    Iteration 2 of the inner loop.
    Iteration 3 of the inner loop.
    Iteration 4 of the inner loop.
The end of iteration 1 of the outer loop.
The start of iteration 2 of the outer loop.
    Iteration 1 of the inner loop.
    Iteration 2 of the inner loop.
    Iteration 3 of the inner loop.
    Iteration 4 of the inner loop.
The end of iteration 2 of the outer loop.
The start of iteration 3 of the outer loop.
    Iteration 1 of the inner loop.
    Iteration 2 of the inner loop.
    Iteration 3 of the inner loop.
    Iteration 4 of the inner loop.
The end of iteration 3 of the outer loop.

我的代码:

#include <stdio.h>

main()
{
    int i, j;
    i = 1;
    j = 1;

    while (i <= 3) {
        printf("The start of iteration %d of the outer loop.\n", i);
        do {
            printf("Iteration %d of the inner loop.\n", j);
            j++;
        } while (j <= 4);
        printf("The end of iteration %d of the outer loop.\n", i);
        i++;
    }
}

输出:

The start of iteration 1 of the outer loop.
Iteration 1 of the inner loop.
Iteration 2 of the inner loop.
Iteration 3 of the inner loop.
Iteration 4 of the inner loop.
The end of iteration 1 of the outer loop.
The start of iteration 2 of the outer loop.
Iteration 5 of the inner loop.
The end of iteration 2 of the outer loop.
The start of iteration 3 of the outer loop.
Iteration 6 of the inner loop.
The end of iteration 3 of the outer loop.

我错过了什么吗?

【问题讨论】:

  • 你没有在它的循环中初始化 j。

标签: c++ nested-loops


【解决方案1】:

您从未在第二次设置中将 j 重置为 1。所以你不断增加它,内部循环只运行一次,因为它不满足你的循环条件。

你可以这样添加:

while (i <= 3) {
    printf("The start of iteration %d of the outer loop.\n", i);
    j = 1;
    // ^^^
    do {
        printf("Iteration %d of the inner loop.\n", j);
        j++;
    } while (j <= 4);
    printf("The end of iteration %d of the outer loop.\n", i);
    i++;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-11
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多