2016-10-19 50 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; 
}