2015-03-03 32 views
-2

我以前解決如何繪製在C矩形,現在有修改程序來繪製三角形看起來像......如何使用+,繪製在C三角形 - ,|和

+ 
|\ 
| \ 
| \ 
| \ 
+----+ 

任何幫助非常感謝,因爲我一直試圖這樣做幾個小時!下面是到目前爲止我的代碼:

int main() 
{ 
    int rows, cols, x, y; 
    rows = 5; 
    cols = 5; 
    for (x=0; x<rows; x++){ 
     for (y=0; y<cols; y++){ 
      if(y==0 && x==0) 
       printf("+\n"); 
      if(y==0) 
       printf("|\n"); 
      if(x==rows - 1 && y==0) 
       printf("+"); 
      if(x==rows - 1) 
       printf("-"); 
      if(x==rows - 1 && y==cols - 1) 
       printf("+"); 
      if(x==y) 
       printf("\\"); 
      else if(x!=rows-1) 
       printf(" "); 
     } 
    } 
    return 0; 
} 
+0

我認爲這問題屬於[代碼評論](http://codereview.stackexchange.com/) – 2015-03-03 08:09:23

+0

@Turtlechase爲什麼行和列等於5,例如圖片中三角形的高度等於6? – 2015-03-03 08:44:30

回答

1

交錯顯示它們,如下所示:

#include <stdio.h> 

int main(void) { 
    int i=0,j=0; 
    printf("+\n"); 
    for(i=0;i<5;i++) 
    { 
     if(i==4) 
     printf("+"); 
     else 
     printf("|"); 
     j=i; 
     while(j--) 
     { 
      if(i==4) 
      { 
      printf("-"); 
      } 
      else 
      printf(" "); 
     } 
     if(i==4) 
     printf("+"); 
     else 
     printf("\\"); 
     printf("\n"); 
    } 
    return 0; 
} 

輸出:

+ 
|\ 
| \ 
| \ 
| \ 
+----+ 
1

頂行是單個+,並且可以被視爲一個異常。

其餘各行遵循

start char 
filler chars 
end char 

可預測的模式的最後一行從他人處僅在於它使用了不同的字符集不同。所以一種解決方案是聲明一個數組來保存兩個字符集,並在最後一行切換字符集。

#include <stdio.h> 
#define N 5 

int main(void) 
{ 
    char charset[2][3] = { { '|', ' ', '\\' }, { '+', '-', '+' } }; 
    int s = 0; 

    printf("+\n");       // output the first row 
    for (int row = 0; row < N; row++) 
    { 
     if (row == N-1)      // switch character sets on 
      s = 1;        // the last row 

     putchar(charset[s][0]);    // output the first character 
     for (int col = 0; col < row; col++) 
      putchar(charset[s][1]);   // output the filler characters 
     printf("%c\n", charset[s][2]);  // output the last character 
    } 
} 
1

捕捉!:)

#include <stdio.h> 

int main(void) 
{ 
    while (1) 
    { 
     printf("Enter height of triangle (0 - exit): "); 
     size_t height = 0; 

     scanf("%zu", &height); 

     if (!height) break; 

     size_t i = 0; 

     printf("\n+\n"); 

     while (++i < height - 1) 
     { 
      printf("|%*c\n", i, '\\'); 
     } 

     if (i < height) 
     { 
      printf("+"); 
      while (--i) printf("-"); 
      printf("+\n"); 
     } 
    } 

    return 0; 
} 

如果進入sequantially 6,5,4,3,2,1,0,那麼該程序輸出將是

Enter height of triangle (0 - exit): 6 
+ 
|\ 
| \ 
| \ 
| \ 
+----+ 
Enter height of triangle (0 - exit): 5 
+ 
|\ 
| \ 
| \ 
+---+ 
Enter height of triangle (0 - exit): 4 
+ 
|\ 
| \ 
+--+ 
Enter height of triangle (0 - exit): 3 
+ 
|\ 
+-+ 
Enter height of triangle (0 - exit): 2 
+ 
++ 
Enter height of triangle (0 - exit): 1 
+ 
Enter height of triangle (0 - exit): 0