打印二维阵列

Printing 2D arrays?

本文关键字:二维 阵列 打印      更新时间:2023-10-16

我遇到了打印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;
}

三个问题:

  1. 数组索引从0开始
  2. NumColumn, NumRow未初始化
  3. 语法错误[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++)
    {               ^^^^
        //...