[英]Nested “for” loops c++
在理解嵌套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;
此外,還有兩個錯誤。
int max ;
應該在for的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加到不存在的值。
如其他答案中所述,您的最大計數器未初始化。 此外,您實際上並不需要它,因為您已經讓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未設置為初始值。
它在第一個循環內部聲明,然后在第二個循環中使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.