嵌套用于数字沿列向下的循环
Nested for-loops with numbers going down columns
所以,这里显然是新手。。。我的目标是输出一个包含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
}
编辑:固定
相关文章:
- 用于C++中带有数组和指针的循环
- 并行用于C++17中数组索引范围内的循环
- 用于循环编译的 constexpr
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- 删除功能不适用于串行通信后多个循环中的多个实例
- C++ for 循环,用于反转数字 10 - 99
- C++用于循环跳过向量的元素?
- OpenMP 内部的函数调用用于循环
- C++11 基于范围的 for 循环,用于 std::list
- 循环中的线程 Runnin 用于对 c++ 中的数字求和
- 将 mmap 内存用于开销非常低的循环缓冲区
- 用于循环访问多个集合的数据结构
- 一个 2D 数组,并按行存储值.第一个循环用于行索引,第二个循环用于列索引
- Leetcode C++用于循环条件
- 相同的 for 循环适用于其他项目,但不适用于此项目。为什么?
- C++ 中用于二维数组的 for-each 循环
- 打开 MP 三用于减少的循环
- 虽然循环不适用于数组应用程序
- 用于增加 ASCII 值的循环
- 这种无操作 while 循环用于断言宏的原因是什么?