嵌套"for"循环 c++

Nested "for" loops c++

本文关键字:c++ 循环 for 嵌套      更新时间:2023-10-16

为了理解嵌套for循环的工作方式,我编写了一个程序,它接受一个输入并显示一个金字塔形的输入值,如下所示:

1
22
333
4444

它只显示金字塔的高度,但不显示第二个for循环中写入的部分

下面是代码(经过修改,但还没有需要的结果)

#include <iostream>
using namespace std;
int main(void)
{
    int num;
    cout << "Enter the number of pyramid" << endl ;
    cin >> num ;
    for (int i = 0; i < num ; i++)
    {
        int max;
        for (int j = 0 ; j <= max ; j++)
        {
            cout << j ;
        }
        cout  << endl ;
        max++ ;
    }
    system("PAUSE");
    return 0;
}
#include <iostream>
 using namespace std;
 int main(void)
  {
    int num ;
    cout << "Enter the number of pyramid" << endl ;
    cin >> num ;
    for (int i = 0; i < num ; i++)
    {
      int max  = i +1; //change 1
      for (int j = 0 ; j < max ; j++)
      {
        cout << max; //change 2
      }
      cout  << endl ;
      //max++ ; //change 3
    }
    system("PAUSE") ;
    return 0;
}

你应该初始化max为0。

int max = 0;

另外还有两个bug。

int max ;
  1. 应该在for循环i之前声明(否则max被定义为始终为0)

  2. 在内循环中打印i,而不是j。

首先,请尝试在你的代码中有一个合适的结构:

#include <iostream>
using namespace std;
int main(void)
{
   int num;
   cout << "Enter the number of pyramid" << endl;
   cin >> num;
   for(int i = 0; i < num; i++)
   {
      int max;
      for(int j = 0; j <= max; j++)
      {
         cout << j;
      }
      cout  << endl;
      max++;
   }
   system("PAUSE");
   return 0;
}

和你的错误:将int max;修改为int max = 0;

正如在其他答案中所述,您的max计数器未初始化。此外,你并不真的需要它,因为你已经有i做同样的任务:

for (int i = 1; i <= num; i++)
{
    for (int j = 0; j < i; j++)
    {
        cout << i;
    }
    cout << endl;     
}

除非您真的想打印类似于0 01 012 0123这样的内容,否则这就是您要找的代码:

for (int i = 1; i <= num; i++)
{
  for (int j = 0; j < i; j++)
    cout << i;
  cout << endl;
}

max未设置为初始值

在第一个循环中声明,然后在第二个循环中使用。