嵌套For循环到Do while循环

Nested For loop to Do while Loop

本文关键字:循环 while Do 嵌套 For      更新时间:2023-10-16

你好,我看了关于家庭作业问题的指导方针,上面说要清楚地说明这是家庭作业。这是作业,我花了45分钟一遍又一遍地尝试。我遇到了瓶颈,需要帮助。

我的任务是将这段来自双For循环的代码转换为嵌套在For循环中的while循环。我已经成功地完成了。然而,第三部分是使用该代码并将外部for循环变成do while循环。输出需要每行增加一个"#",如果输入为"4"

#
##
###
####

下面是我写的代码,我需要把外部的for循环变成一个do while循环:

int main()
{
    int side;
    cout << "Enter a number: ";
    cin >> side;
    for (int i = 0; i < side; i++)
    {
        int j = i;
        while(j >= 0)
        {
            cout << "#";
            j--;
        }
        cout << "n";
    }
}

这是我到目前为止的尝试:

int main()
{
    int side;
    int i;
    cout << "Enter a number: ";
    cin >> side;
    int j=side;
    do
    {
        while(j >= 0)
        {
            cout << "#";
            j--;
        }
        cout << "n";
        i++;
    }
    while(j >= side);
}

我的老师说,只要解释了代码,我明白它是如何工作的,这是可以的。任何帮助都将非常感激。谢谢。

你犯的第一个错误是:

int i; //not initialized!
/*...*/
i++;

,你甚至没有在do-while条件中使用它。

所以while(j >= side);> while (i >= side);

事实上,这也不是真的。因为边是输入,你想让i检查它是否小于而不是大于。所以是while (i < side);

另一件事是int j=side;,当你递减j时,它将永远不会重置,所以你必须将它设置到你的do-while循环中,并使用i而不是....初始化它

总之,这里是完整的代码:

#include <iostream>
using namespace std;
int main()
{
    int side;
    int i = 0;
    cout << "Enter a number: ";
    cin >> side;
    do
    {
        int j = i;
        while (j >= 0)
        {
            cout << "#";
            j--;
        }
        cout << "n";
        i++;
    } while (i < side);
    return 0;
}

示例输出:

Enter a number: 10
#
##
###
####
#####
######
#######
########
#########
##########

我建议

int main()
{
    int side;
    int i = 0;
    cout << "Enter a number: ";
    cin >> side;
    do
    {
        int j = i;
        while(j >= 0)
        {
           cout << "#";
           j--;
        }
        cout << "n";
        i++;
    }while(i < side)
}

for循环通常由初始化(i=0)、停止条件(i < side)和递增(i++)组成;为什么你不再使用i了?

  • while(j >= side);应该是while(i <= side);
  • j应在外循环(j = i;)的每次迭代中初始化
  • int j=side;是不必要的。

一个友好的建议-描述性地命名你的变量和函数- rowcolumnij好得多。

上面的答案解决了你的问题,但让我告诉你一个更简单的方法:

int main()
{
    int side;
    std::cout << "Enter a number: ";
    std::cin >> side;
    int row = 1;
    do
    {
        int col = 0;
        while (col++ != row)
        {
            std::cout << "#";
        }
        std::cout << "n";
    } while (row++ != side); //This way, the condition is checked (row != side), and then row is incremented
}