我正在编写一个程序,其中使用了 5x5 数组,实际上我遇到了一个错误。
为了找到它,我尝试简化程序,改写另一个程序,其中我只想使用数组简单地显示数字 1 到 25。
#include <iostream>
#include <conio.h>
using namespace std;
main()
{
long int a[4][4];
int m=1;
for(int i=0;i<5;i++)
{for(int j=0;j<5;j++)
{a[i][j]=m;
m=m+1;
}
}
for(int i=0;i<5;i++)
{for(int j=0;j<5;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
getch();
}
我实际得到的是:
1 2 3 4 6
6 7 8 9 11
11 12 13 14 16
16 17 18 19 21
21 22 23 24 25
然而,当我尝试不同的东西并放置一个 cout<<a[i][j];
在 a[i][j]=m;
之后并删除了第二部分,我没看错。
我在这里遗漏了什么吗?
最佳答案
您的数组是 4 x 4,但您将其视为 5 x 5。您的代码具有未定义的行为。你的循环应该只计算到 i < 4
和 j < 4
,或者您需要将数组声明为 long int a[5][5];
.
顺便说一下,main
应该有一个返回类型,它应该是 int
.其他任何东西都是非标准的。
关于c++ - 在 C++ 中使用数组时出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18419196/