2014-11-06 157 views
1

如何使用while循環而不是for循環寫入相同的代碼?將簡單的for循環轉換爲while循環?

int n; 
cin >> n; 

for (int i = 1; i <= n; i++) { 
     for (int j = n; j >= i; j--) { 
      cout << j; 
     } 
     cout << endl; 
    } 

這是我的嘗試,但它沒有達到同樣的效果。我不知道爲什麼。

int n; 
cin >> n; 
int i = 1; 
int j = n; 

    while (i <= n) { 
     while (j >= i) { 
      cout << j; 
      j--; 
     } 
     i++; 
     cout << endl; 
    } 
+0

'int j = n;'必須在循環之間 – sp2danny 2014-11-06 07:34:25

回答

1

您必須在while(j >= i)循環前重置j

while (i <= n) { 
    j = n; //<<<<<<<< Reset j to the starting value 
    while (j >= i) { 
     cout << j; 
     j--; 
    } 
    i++; 
    cout << endl; 
} 
+1

我覺得很愚蠢。謝謝。 – Learner 2014-11-06 07:37:40