递归的Sierpinski三角形不是递归的

我正在为递归的Sierpinski三角形做一个程序,并且不知道如何更改数组xm[]ym[]中的点以便执行此操作。 更具体地说,当我运行这个程序时,只绘制一个带有一个蓝色内三角的轮廓三角形。 任何帮助将不胜感激!

 public class recursiveSierpinski { public static void draw(int n, double x0, double y0, double x1, double y1, double x2, double y2) { // if reach base case, method return if (n==0) return; // define array xm, ym to store x and y values of midpoints double [] xm = new double[3]; double [] ym = new double[3]; // assign midpoints' values to xm and ym xm[0]= (x0+x1)/2; xm[1]= (x1+x2)/2; xm[2]= (x2+x0)/2; ym[0]= (y0+y1)/2; ym[1]= (y1+y2)/2; ym[2]= (y2+y0)/2; StdDraw.setPenColor(StdDraw.BLUE); StdDraw.filledPolygon(xm, ym); //this makes triangle xm[0]=xm[0]/2.0; ym[0]=ym[0]/2.0; xm[1]=xm[1]/2.0; ym[1]=ym[1]/2.0; xm[2]=xm[2]/2.0; ym[2]=ym[2]/2.0; draw(n,xm[0],ym[0],xm[1],ym[1],xm[2],ym[2]); draw(n,xm[1],ym[1],xm[2],ym[2],xm[0],ym[0]); draw(n,xm[2],ym[2],xm[0],ym[0],xm[1],ym[1]); // recursively draw the sub triangles (?) } public static void main(String[] args) { // N levels of recursion int N = Integer.parseInt(args[0]); // outline the triangle 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, t); StdDraw.line(0.5, t, 0.0, 0.0); draw(N, 0.0, 0.0, 0.5, t, 1.0, 0.0); } } 

尝试这个:

 public class recursiveSierpinski { public static void draw(int n, double x0, double y0, double x1, double y1, double x2, double y2) { // if reach base case, method return if (n==0) return; // define array xm, ym to store x and y values of midpoints double [] xm = new double[3]; double [] ym = new double[3]; // assign midpoints' values to xm and ym xm[0]= (x0+x1)/2; xm[1]= (x1+x2)/2; xm[2]= (x2+x0)/2; ym[0]= (y0+y1)/2; ym[1]= (y1+y2)/2; ym[2]= (y2+y0)/2; StdDraw.filledPolygon(xm, ym); //this makes triangle draw(n-1,xm[0],ym[0],xm[1],ym[1],x1,y1); draw(n-1,xm[1],ym[1],xm[2],ym[2],x2,y2); draw(n-1,xm[2],ym[2],xm[0],ym[0],x0,y0); } public static void main(String[] args) { // N levels of recursion int N = Integer.parseInt(args[0]); // outline the triangle double t = Math.sqrt(3.0) / 2.0; StdDraw.setPenColor(StdDraw.BLACK); // fill arrays initially to draw black solid TRIANGLE xm, ym = 0.0, 0.0, 0.5, t, 1.0, 0.0 StdDraw.filledPolygon(xm, ym); StdDraw.setPenColor(StdDraw.WHITE); draw(N, 0.0, 0.0, 0.5, t, 1.0, 0.0); } } 

你不应该再改变它们了。 假设你的参数代表三角形的点,在你的fillPolygon调用之后你已经计算了你的点数。

对于三角形ABC,您已经找到了中点AB,BC,AC。

因此,您可以在三角形A-AB-AC,三角形AB-B-BC和三角形BC-C-AC上调用Sierpinski。

就代码而言,您将在fillPolygon()调用之后删除对xm和ym的更改,并调用draw。 另请注意,您需要n-1,否则您将无限递归。

 draw(n-1,x0,y0,xm[0],ym[0],xm[2],ym[2]); draw(n-1,xm[0],ym[0],x1,y1,xm[1],ym[1]); draw(n-1,xm[1],ym[1],x2,y2,xm[0],ym[0]); 

关于托马斯的好答案

它应该是

 draw(n-1,x0,y0,xm[0],ym[0],xm[2],ym[2]); draw(n-1,xm[0],ym[0],x1,y1,xm[1],ym[1]); 
  draw(n-1,xm[1],ym[1],xm[2],ym[2],x2,y2); 

因此根据我的最后一行应该是不同的。