嵌套的 for 循环,数字向下列

Nested for-loops with numbers going down columns

所以,显然是新手...我的目标是输出一个 table 八列十行的数字 1 到 80。这必须使用 嵌套 for 循环来完成(对于作业)。这是我目前所拥有的:

int num = 1; //start table of numbers at one

for (int row = 0; row < 10; row++) //creates 10 rows
{
    for (int col = 0; col < 8; col++) //creates 8 columns
    {
        cout << num << "\t" ; //print each number
        num = num + 10;
    }

    cout << num;
    num++;

    cout << endl; //output new line at the end of each row
}

但我的输出应该是这样的:

1 11 21 31 41 51 61 71
2 12 22 32 42 52 62 72
...
10 20 30 40 50 60 70 80

我的方向是否正确?我该怎么做呢?现在,我打印时只有第一行是正确的。

您只需:

int num = 1; //start table of numbers at one

for (int row = 0; row < 10; row++) //creates 10 rows
{
    for (int col = 0; col < 8; col++) //creates 8 columns
    {
         cout << num << "\t" ; //print each number
         num += 10;
    }
num = row + 2;
cout << endl; //output new line at the end of each row
}

编辑:已修复

我们初学者应该互相帮助。尝试以下

#include <iostream>
#include <iomanip>

int main()
{
    const int ROWS = 10;
    const int COLS = 8;

    for ( int row = 0; row < ROWS; row++ )
    {
        for ( int col = 0; col < COLS; col++ )
        {  
            std::cout << std::setw( 2 ) << row + 1 + ROWS * col << ' ';
        }
        std::cout << std::endl;
    }        

    return 0;
}

输出为

 1 11 21 31 41 51 61 71 
 2 12 22 32 42 52 62 72 
 3 13 23 33 43 53 63 73 
 4 14 24 34 44 54 64 74 
 5 15 25 35 45 55 65 75 
 6 16 26 36 46 56 66 76 
 7 17 27 37 47 57 67 77 
 8 18 28 38 48 58 68 78 
 9 19 29 39 49 59 69 79 
10 20 30 40 50 60 70 80 

除了变量 num 被错误地更改外,你的方向是正确的。:) 例如在外循环的第一次迭代之后 num 等于(如果我没记错的话) 72.

这是一个更通用的方法,允许设置初始值。

#include <iostream>
#include <iomanip>

int main()
{
    const int ROWS = 10;
    const int COLS = 9;
    const int INITIAL_VALUE = 10;

    for ( int row = 0; row < ROWS; row++ )
    {
        for ( int col = 0; col < COLS; col++ )
        {  
            std::cout << std::setw( 2 ) << INITIAL_VALUE + row + ROWS * col << ' ';
        }
        std::cout << std::endl;
    }        

    return 0;
}

程序输出为

10 20 30 40 50 60 70 80 90 
11 21 31 41 51 61 71 81 91 
12 22 32 42 52 62 72 82 92 
13 23 33 43 53 63 73 83 93 
14 24 34 44 54 64 74 84 94 
15 25 35 45 55 65 75 85 95 
16 26 36 46 56 66 76 86 96 
17 27 37 47 57 67 77 87 97 
18 28 38 48 58 68 78 88 98 
19 29 39 49 59 69 79 89 99