我需要创建n次递归sierpinski三角形,其中n是命令行参数。我的程序执行了两次,但是此后的任何操作都可能使某些三角形位于错误的位置或根本不存在。这是我的代码:
public class Sierpinski {
// Height of an equilateral triangle whose sides are of the specified length.
public static double height(double length) {
// WRITE YOUR CODE HERE
double height = (length * Math.sqrt(3.0)) / 2;
return height;
}
// Draws a filled equilateral triangle whose bottom vertex is (x, y)
// of the specified side length.
public static void filledTriangle(double x, double y, double length) {
// WRITE YOUR CODE HERE
double x2 = x - length/4;
double y2 = y + height(length)/2.0;
double x3 = x + length/4;
double y3 = y + height(length)/2.0;
double[] xs = {x, x2, x3};
double[] ys = {y, y2, y3};
StdDraw.filledPolygon(xs, ys);
}
// Draws a Sierpinski triangle of order n, such that the largest filled
// triangle has bottom vertex (x, y) and sides of the specified length.
public static void sierpinski(int n, double x, double y, double length) {
// WRITE YOUR CODE HERE
filledTriangle(x, y, length);
if (n == 1){
System.out.println();
}else{
filledTriangle(x, y, length);
n--;
sierpinski(n, x - x/2, y, length/2);
sierpinski(n, x + x/2, y, length/2);
sierpinski(n, x, y + height(length)/2, length/2);
}
}
// Takes an integer command-line argument n;
// draws the outline of an equilateral triangle (pointed upwards) of length 1;
// whose bottom-left vertex is (0, 0) and bottom-right vertex is (1, 0); and
// draws a Sierpinski triangle of order n that fits snugly inside the outline.
public static void main(String[] args) {
// WRITE YOUR CODE HERE
int n = Integer.parseInt(args[0]);
int length = 1;
double t = Math.sqrt(3.0) / 2.0;
StdDraw.line(0.0, 0.0, 1.0, 0.0);
StdDraw.line(1.0, 0.0, 0.5, height(length));
StdDraw.line(0.5, height(length), 0.0, 0.0);
double x = 0.5;
double y = 0.0;
sierpinski(n, x, y, length);
}
}
该程序适用于n = 1和n = 2,但是任何包含n = 3的内容都会破坏该程序。