Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
嵌套的“为”循环C++_C++_Loops_Initialization - Fatal编程技术网

嵌套的“为”循环C++

嵌套的“为”循环C++,c++,loops,initialization,C++,Loops,Initialization,在理解嵌套for循环工作的过程中,我编写了一个程序,该程序接受一个输入并显示一个金字塔,直到输入值如下: 1 22 333 4444 它只显示金字塔的高度,但不显示第二个for循环中的写入部分 这是修改后的代码,但所需的结果尚未确定 #include <iostream> using namespace std; int main(void) { int num; cout << "Enter the number of pyramid" <&l

在理解嵌套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;
}

您应该将max初始化为0

int max = 0;
另外还有两个bug

int max ;
应该在i的for循环之前声明。否则,max将始终定义为0

在内部循环中打印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;
您不能将1添加到不存在的值。

如其他答案中所述,您的最大计数器未初始化。此外,您并不真的需要它,因为您已经让我执行相同的任务:

#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;
}
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未设置为初始值


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

您还没有初始化MAX请在请求帮助之前花时间正确缩进代码。@Jack这是一个有效的答案。将其发布为1。您可以将1添加到单位化值,但这是未定义的行为-这还不够,他在最大值超出范围之前增加了最大值,所以需要进行另一个更改。@riv:谢谢,需要两个更改。如果我将金字塔的高度设为5,我现在理解我的错误。例如,它只显示高度4,一切正常。小的更改可能会影响大的:已解决的问题,现在一切都好了,上帝,这些小条件对理解是至关重要的,如果有人给我提供一个链接,让我理解这些for循环条件,我会很有帮助。很好。你需要读一本好的C++初学者的书。不要忘记接受这两个答案中的任何一个。那么max++是无用的,正如@rivmax所说的那样,在下一次迭代中超出了范围,所以在那里增加它没有任何作用。要么在循环外声明max,要么干脆用i+1来代替。@rajraj-是的,我复制了OP,但忘了更改它。