2016-05-14 47 views
-1

所以我一直試圖在網格中畫一個空心方塊。我使用寬度爲10和高度爲5的二維數組創建了網格原來的字符「*」。當從給定的座標改變每個數組的值時,我從座標的正方形畫出正方形的左上角。問題是,當我印刷它出來只有一半的外部完成。Grid中的空心方塊

我錯過了一個條件或太多的條件時,重寫網格數組的部分?感謝您的幫助。

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

的問題是在雙for在這裏你設置爲'o'方形的邊框。

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(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))和(a)在邊界的情況下,設置c (即'o'),(b)另有設置'*'

好。

但是你不能因爲np範圍從x-1y-1,包括,以x+size-1y+size-1排除

所以n不能是x+size-1:上限(包括)的限制是x+size-2。並且p不能是y+size-1:上限(包含)限制爲y+size-2

結論:你的測試應該是

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

P.S:對不起,我的英語不好

+0

對不起,我當時的想法是,我想我只是算錯。非常感謝你的幫助。 – pandalot