2016-10-19 282 views
-1

我有一個賦值使用嵌套for循環來打印5行和3列的二維數組的索引,而不使用數組。關於嵌套for循環

#include <iostream> 
using namespace std; 

int main() 
{ 
    int row; 
    int column; 
    cout << "Counting with nested loops: indices of row, column" << endl << endl; 
    for (row = 1; row <= 5; row++) 
    { 
     for (column = 1; column <= 3; column++) 
     { 

     } 
     cout << row << "," << column << "\t" << row << "," << column << "\t" << row << "," << column << "\t" << endl; 
    } 
    cout << "\n\n\n" << endl; 
    return 0; 
} 

這是我到目前爲止的代碼。我的目標是打印

1,1 1,2 1,3

2,1 2,2 2,3

等。當我運行該程序將打印

1,4 1,4 1,4

2,4 2,4 2,4

所以我行部分正確。任何人都可以幫我弄清楚我的錯誤是什麼?

+0

如果沒有數組,將會打印什麼? –

+0

那麼你的數據存儲在哪裏? –

+3

@AndreasWalter我相信這個問題很清楚:「打印出二維數組的索引」 - 他必須打印數組的索引而不是內容。也許有人說過他們實際上的意思時,也是少數幾次之一。 :) – davmac

回答

0

需要調用打印只一次,但內部循環像這裏面:

for (row = 1; row <= 5; row++){ 
    for (column = 1; column <= 3; column++){ 
     std::cout << row << "," << column << "\t"; 
    } 
    std::cout << std::endl; 
} 
+0

沒有以正確的格式打印。它印的數量比我應有的要多得多。 – Subparman

+0

編輯打印你想要的 –

+1

我當然感謝你的幫助。我真的不明白我還想念什麼,你有沒有一個簡短的解釋時刻?再次感謝 – Subparman

0

這是你必須寫代碼:

int main() { 
    int row; 
    int column; 

    cout << "Counting with nested loops: indices of row, column" << endl << endl; 

    for (row = 1; row <= 5; row++) { 
     for (column = 1; column <= 3; column++) { 
      cout << row << "," << column << "\t"; 
     } 
     cout << endl; 
    } 

    cout << "\n\n\n" << endl; 
    return 0; 
} 

這是因爲你必須打印裏面 secondo循環,而不是外面。

0

其他人已經回答了這個問題,但我想添加一些建議,讓事情在將來考慮。

首先引入循環變量,例如int row;你還沒有初始化它們,只需要在for循環中將它們聲明在那裏。 然後,在for循環之外,它們將不可見,這可以避免在循環結束後打印錯誤(通過cout)。

這也是值得考慮的循環計數器。從0開始是常規的。此外,數組的索引將從0開始並運行到n-1。所以你應該考慮打印0,1,...而不是1,2,......如果你打算使用它來遍歷一個數組。

#include <iostream> 
using namespace std; 

int main() 
{ 
    cout << "Counting with nested loops: indices of row, column" << endl << endl; 
    for (int row = 0; row < 5; row++) //<--- note start at 0 and stop BEFORE n 
    { 
     for (int column = 0; column < 3; column++) //<--- ditto 
     { 
      cout << row << "," << column << "\t"; 
     } 
     //cout << row << "," << column << "\t" 
       << row << "," << column << "\t" 
       << row << "," << column << "\t" << endl; 
       // Now compile error 
       // And clearly was going to just give the same value 
       // for row and column over and over 
     cout << '\n';//added to break each row in the output 
    } 
    cout << "\n\n\n" << endl; 
    return 0; 
}