所以我在这里有一个简单的小代码,试图输入n
,然后创建一个大小为n-1
的数组,其格式如下:
n = 7
1 0 0 0 0 0 <- The first line is always like this
1 2 1 0 0 0
0 1 2 1 0 0
0 0 1 2 1 0
0 0 0 1 2 1
0 0 0 1 -2 1 <- The last line is always like this
代码是:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int n,i,j;
cout<<"input jumlah partisi : "; cin>>n; cout<<endl;
int alah [n-1] [n-1];
for(i=0;i<=n-2;i++){
for(j=0;j<=n-2;j++){
alah[i][j]=0;
if(i==j){
alah[i][j+1]=1; // <<<<<< Here is the problem
alah[i][j]=2;
alah[i][j-1]=1;
}
//Last line
if(i==n-2){
if(i==j){
alah[i][j]=1;
alah[i][j-1]=-2;
alah[i][j-2]=1;
}
}
//First line
if(i==0){
if(i==j){
alah[i][j]=1;
}
}
}
}
for (i=0;i<=n-2;i++){
for(j=0;j<=n-2;j++){
cout<<alah[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
return 0;
}
相反,它会输出(我已尝试过Windows,Linux和Ideone):
1 0 0 0 0 0
1 2 0 0 0 0
0 1 2 0 0 0
0 0 1 2 0 0
0 0 0 1 2 0
0 0 0 1 -2 1
这里发生了什么?附加说明:如果我用alah [i] [j-n + 1]更改alah [i] [j + 1],它将会产生一个近乎完美的代码,我知道这是因为它填充了前一行而不是当前行线。顺便说一句,关于代码的无效性,我已经提高了效率,但我想知道为什么这个特定的代码不起作用。谢谢。
答案 0 :(得分:0)
你的错误是你的所有工作都被下一个循环迭代所取消:
alah[i][j]=0;
我会先将整个数组初始化为0,从而避免了这个问题。