2017-09-16 72 views
-4

所以我在这里有一个简单的小的代码,试图输入n然后使用大小n-1被格式化这样的数组:为什么alah [j + 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],它会产生一个近乎完美的代码,我知道这是因为它填充了前一行而不是当前行线。顺便说一句,关于代码的低效率,我做了一些更高效的工作,但我想知道为什么这个特定的代码不起作用。谢谢。

+2

我鼓励您学习如何使用调试器 – Fureeish

+0

切勿使用'使用名称空间标准;'。相反,对每个*个人*对象使用'std :: cout;'等等,或者甚至在使用它们时限定它们。 – o11c

+0

为什么字段大小为n-1? – 2017-09-16 18:50:35

回答

0

你的错误是,所有的工作是由一个循环周期撤销:

alah[i][j]=0; 

我已经第一次初始化整个数组为0,从而避免了这个问题。