2015-10-15 94 views
1

我正在研究一個打印基於用戶輸入的高度和分形水平的謝爾賓斯基三角形的程序。下面是我的程序應該高度8的輸入,並分等級1產生:Sierpinski三角形調試--- C

 * 
     *** 
    ***** 
    ******* 
    *  * 
    ***  *** 
***** ***** 
******* ******* 

這是我到目前爲止有:

#include <stdio.h> 
#include <stdlib.h> 

int main(int argc, const char *argv[]) { 

    int height, draw, errno, fractal_level; 

    char *p; 
    char *q; 
    errno = 0; 
    height = strtol(argv[1], &p, 10); 
    fractal_level = strtol(argv[2],&q, 10); 
    if (errno != 0 || p == argv[1]) { 
     printf("ERROR: Height must be integer.\n"); 
     exit(1); 
    } 
    else if (errno != 0 || q == argv[2]) { 
     printf("ERROR: Fractal Level must be integer.\n"); 
     exit(1); 
    } 
    int x,y; 
    x=(2*height-1)/2; 
    y=(2*height-1)/2; 
    printf("x: %d y: %d \n", x, y); 
    drawSier(height, fractal_level, x, y); 

    return 0; 
} 

int drawSier(height, fractal_level, x, y) { 

    //If the fractal level is zero, it's just a normal triangle. 
    if (fractal_level==0) 
    { 
     drawTriangle(height, x, y); 
    } 
    //the function calls itself, but with a slight variance 
    //in the starting point of the triangle, for the top, bottom left, and bottom right 
    else { 
    //top 
    drawSier(height/2, fractal_level-1, x, y); 
    //bottom left 
    drawSier(height/2, fractal_level-1, x-height/2, y-height/2); 
    //bottom right 
    drawSier(height/2, fractal_level-1, x+height/2, y-height/2); 
    } 
} 

int drawTriangle(height, x, y){ 

    if (height<1) { 
     printf("ERROR: Height too small.\n"); 
     exit(1); 

    } 
    else if (height>129) { 
     printf("ERROR: Height too large.\n"); 
     exit(1); 
    } 

    for (int i = 1; i <= height; i++) 
    { 
     int draw=0; 

     // this 'for' loop will take care of printing the blank spaces 
     for (int j = i; j <= x; j++) 
     { 
      printf(" "); 
     } 
     //This while loop actually prints the "*"s of the triangle by multiplying the counter 
     //by 2R-1, in order to output the correct pattern of stars. This is done AFTER the for 
     //loop that prints the spaces, and all of this is contained in the larger 'for' loop. 
     while(draw!=2*i-1) { 
       printf("*"); 
       draw++; 
     } 
     draw=0; 
     //We print a new line and start the loop again 
     printf("\n"); 
    } 

return 0; 
} 

這裏是我的方案目前正在與生產相同的輸入:

 * 
     *** 
    ***** 
    ******* 
    * 
    *** 
***** 
******* 
      * 
      *** 
     ***** 
     ******* 

我不確定發生了什麼問題。這似乎是y變量的問題。

+0

我已經盯着這個小時,並嘗試重寫循環三次。沒有什麼能產生我所需要的。也許如果你能給我一些我需要看的地方,而不是把傳統的迂腐堆棧溢出評論,這可能會更有幫助:) –

+1

你的代碼設置的方式,你一次只能打印一個三角形一組給定的行。您需要重構結構,以便您可以在一條線上打印多個三角形,即打印三角形1的線1,空出,打印三角形2的線1,換行... – dbush

+0

我建議您在內存中完成所有繪圖通過填充一個跟蹤每個空間是空還是滿的數組),然後打印出該數組。 –

回答

1

y傳遞給drawTriangle()但該函數不使用它。它只是用三角形打印新的線條,在之前打印的東西下面。

您可以使用控制檯控制代碼在打印前將光標移動到所需的位置(注意不要覆蓋先前打印的輸出),也可以先在內存中創建完整圖像,然後僅在結束。

+0

我假設通過 「在內存中創建」您的意思是把所有的信息放在一個數組中。不過,我在調用帶有數組參數的函數時遇到了一些麻煩。 –