2013-06-13 160 views
0

就明白的嵌套for循環我寫了一個程序,它需要一個輸入工作,並顯示一個金字塔高達像這樣的輸入值的方式:嵌套「for」循環C++

1 
22 
333 
4444 

它顯示只是高度的金字塔,但它沒有顯示在第二個循環的書面部分。

下面是代碼(修改後,但所需的結果目前還沒有)

#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; 
} 
+8

您還沒有初始化最大 – Jack

+3

在請求幫助之前,請花時間正確縮進您的代碼。 – meagar

+0

@傑克這是一個有效的答案。將它張貼爲一個。 – Maroun

回答

2

你應該初始化最大爲0

int max = 0; 

另外還有兩個更多的錯誤。

int max ; 
  1. 前應在for循環中聲明瞭我。 (否則,max始終定義爲0)

  2. 在內部循環中打印i,而不是j。

+2

這還不夠,他在超出範圍之前正在增加max,所以需要進行其他更改。 – riv

+0

@riv:謝謝,需要進行兩項更改。 – PermanentGuest

+0

我現在理解我的錯誤,如果我給金字塔的高度爲5例如它只是顯示高度4,一切都沒問題。 –

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; 

     for(int j = 0; j <= max; j++) 
     { 
     cout << j; 
     } 

     cout << endl; 
     max++; 
    } 

    system("PAUSE"); 
    return 0; 
} 

而你的錯誤: 更改int max;int max = 0; 您不能添加1到一個不存在的價值。

+1

您可以將1添加到單位化值,但它是未定義的行爲;-) – TemplateRex

3
#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; 
} 
+1

+1。第一個正確的答案。 – Maroun

+1

那麼'max ++'是無用的,正如@riv – Offirmo

+1

所說的那樣'max'會在下一次迭代時超出範圍,所以在那裏增加它什麼也不做。要麼在循環外聲明'max',要麼簡單地使用'i + 1'。 – riv

1

正如其他答案中所述,您的最大計數器未初始化。此外,你並不真的需要它,因爲你已經有i做同樣的任務:

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

    cout << endl;  
} 
+0

我認爲他想要打印'i + 1',而不是'j'。 –

+0

@rajraj - 是的,我複製了OP的對面,忘記了改變它。 – Utopia

0

除非你真的想打印出類似這樣0 01 012 0123這是你要找的代碼:

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

max未設置爲初始值。

它在第一個循環中聲明,然後在第二個循環中使用。