2016-05-14 7 views
-1

グリッドの内側に中空の四角形を描こうとしています。私はグリッドを元々 "*"の文字で、幅10と高さ5の2次元配列を使って作成しました。与えられた特定の座標から各配列値を変更するとき、私は四角形の左上隅の座標から四角形を描画します。問題は、それが印刷されたときに外の半分だけが出てしまうことです。グリッドの中空角

グリッドアレイの一部を書き直すときに条件が不足していたり​​、条件が多すぎますか?お手伝いありがとう。

int main(){ 
    char grid[5][10];//initialize array that will be row and column 
    for(int i=0;i<5;i++){ 
     for(int j=0;j<10;j++){ 
      grid[i][j]= '*'; 
     }//for 
    }//for loop to fill grid with asterisk 
    cout << "GRID" << endl << endl; 
    for(int i=0;i<5;i++){ 
     for(int j=0;j<10;j++){ 
      cout << grid[i][j] ; 
     }//for 
     cout << endl; 
    }//for loop to print grid no shapes inside 
    cout << endl << endl; 

    int x = 2; 
    int y = 3; 
    int size = 3; 
    char c = 'o'; 
    //will have a condition here to check if it can fit inside the 
    //grid but this is just to test it will be a member function. 
    for(int n=x-1;n<x+size-1; n++){ 
     for(int p=y-1;p<y+size-1; p++){ 
      if (n == x-1 || n==x+size-1 || p == y-1 || p== y+size-1){ 
       grid[n][p] = c; 
      } 
      else 
       grid[n][p] = '*'; 
     }//for 
    }//for loop to rewrite specific array coordinates with new c 
    cout << "Shape inside grid." << endl; 
    for(int n=0;n<5;n++){ 
     for(int p=0;p<10;p++){ 
      cout << grid[n][p]; 
     }//for 
     cout << endl; 
    }//for loop to print new grid 
    return 0; 
} 
/* 
This is my output: 
********** 
**ooo***** 
**o******* 
**o******* 
********** 

This is what I need: 
********** 
**ooo***** 
**o*o***** 
**ooo***** 
********** 
*/ 

答えて

0

問題は、あなたが'o'に四角形の境界線を設定し、二重forです。

for(int n=x-1;n<x+size-1; n++){ 
    for(int p=y-1;p<y+size-1; p++){ 
     if (n == x-1 || n==x+size-1 || p == y-1 || p== y+size-1){ 
     grid[n][p] = c; 
     } 
     else 
     grid[n][p] = '*'; 
    } 
} 

あなたの意思私はよく理解している場合、ポイントは、境界点(if (n == x-1 || n==x+size-1 || p == y-1 || p== y+size-1))であれば、正方形(for(int n=x-1;n<x+size-1; n++)for(int p=y-1;p<y+size-1; p++))のポイントは、チェック反復トラフで、(a)のボーダーの場合には、cを設定(つまり、'o')、(b)その他の場合は'*'と設定します。

良い。 npの範囲はx-1y-1からであるため、

は、しかし、あなたが含まれ、x+size-1y+size-1に、を除外し、失敗します。

したがってnは、x+size-1にはなりません。上限(含む)はx+size-2です。 py+size-1にできません。上限(含む)はy+size-2です。

結論:あなたのテストは

 if (n == x-1 || n==x+size-2 || p == y-1 || p== y+size-2) 

p.s:私の悪い英語のため申し訳ありません

+0

する必要があります申し訳ありませんが、私はちょうど誤カウントを推測正しい考えを持っていました。手伝ってくれてどうもありがとう。 – pandalot

関連する問題