打印二维阵列
Printing 2D arrays?
我遇到了打印2D数组的问题。这是我的代码,如有任何帮助,将不胜感激。
#include<iostream>
using namespace std;
int main()
{
int NumRow, NumColumn;
int anArray[2][2] = {{1,2},{3,4}};
for (int N_column = 1; N_column < NumColumn; N_column++)
{
for (int N_row = 1; N_row < NumRow; N_row++)
{
cout << anArray[N_row,N_column];
}
}
return 0;
}
三个问题:
- 数组索引从0开始
-
NumColumn
,NumRow
未初始化 - 语法错误
[y,j]
,用[i][j]
试试:
...
int NumRow = 2, NumColumn = 2;
int anArray[2][2] = {{1,2},{3,4}};
for (int N_column = 0; N_column < NumColumn; N_column++)
{
for (int N_row = 0; N_row < NumRow; N_row++)
{
cout << anArray[N_row][N_column];
}
}
...
声明
int NumRow, NumColumn;
,但你从不给它们赋值。使用
int NumRow = 2, NumColumn = 2;
。此外,c数组从0开始,而不是从1开始,因此您也必须更新for循环:
for (int N_column = 0; ...
for (int N_row = 0; ...
最后,更改输出语句,因为需要以不同的方式访问多维数组:
cout << anArray[N_row][N_column];
你的代码中有几个问题:
1st:您声明了NumRow, NumColumn
,但是在使用它们之前没有初始化它们,这会导致未定义行为。
解决方案:初始化它们
NumRow = 2;
NumColumn = 2;
second:数组语法-
cout << anArray[N_row,N_column];
应该是
cout << anArray[N_row][N_column];
第三: c++数组是零索引的,所以你应该像下面这样开始初始化循环控制变量:
for (int N_column = 0; N_column < NumColumn; N_column++)
{ ^^^
for (int N_row = 0; N_row < NumRow; N_row++)
{ ^^^^
//...
相关文章:
- 二维阵列的动态分配
- C2440 使用Shared_ptr创建二维阵列
- 围绕二维阵列做一个圆圈
- 为什么一个二维阵列会导致赛段故障,而另一个则不会导致?
- 二维阵列的名称到底代表什么?
- 返回二维阵列
- 是二维阵列访问/修改时间组
- 如何创建一个具有空值、递减编号系统和.txt文件输入值的二维阵列网格
- 八个皇后二维阵列,带有gotos errror
- C++中的二维阵列
- 使用矢量创建二维阵列
- 编制二维阵列
- 错误:解除分配二维阵列
- 复制二维阵列C++
- 将二维阵列模拟为一维阵列
- 从具有两列的文件中加载二维阵列
- 可调整大小的动态二维阵列的更好解决方案
- 使用二维阵列用C++求解埃拉托色尼筛
- 如何显示非对角线二维阵列元素
- 嵌套阵列或嵌套二维阵列