嵌套用于数字沿列向下的循环

Nested for-loops with numbers going down columns

本文关键字:循环 用于 数字 嵌套      更新时间:2023-10-16

所以,这里显然是新手。。。我的目标是输出一个包含8列和10行的表,其中的数字从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

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

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

#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 

您所需要做的就是:

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
}

编辑:固定