我正在开发一个基于用户输入的高度和分形水平打印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;
}
这是我到目前为止所做的:
*
***
*****
*******
*
***
*****
*******
*
***
*****
*******
以下是我的程序当前使用相同输入生成的内容:
{{1}}
我不确定出了什么问题。这似乎与y变量有关。
答案 0 :(得分:1)
y
已传递给drawTriangle()
,但该功能并未使用它。它只是打印带有三角形的新线条,位于之前打印的内容之下。
您可以使用控制台控制代码在打印前将光标移动到所需位置(注意不要覆盖以前打印的输出),或者您可以先在内存中创建完整图像,最后只将其打印出来