我正在开发一个程序,根据用户输入的高度和分形级别打印一个Sierpinski三角形。以下是我的程序在输入高度8和分形级别1时应产生的结果:

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

这就是我目前所拥有的:
#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变量的问题。

最佳答案

y被传递到drawTriangle()但函数不使用它。它只是用三角形打印新行,在前面打印的东西下面。
您可以使用控制台控制代码在打印前将光标移动到所需位置(注意不要覆盖以前打印的输出),也可以先在内存中创建完整图像,然后在最后才打印出来。

关于c - Sierpinski Triangle调试-C,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33154399/

10-13 02:37