gpt4 book ai didi

java - 递归谢尔宾斯基三角形不递归

转载 作者:行者123 更新时间:2023-12-01 15:38:36 25 4
gpt4 key购买 nike

我正在为递归谢尔宾斯基三角形编写程序,但不知道如何更改数组 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);
}
}

关于java - 递归谢尔宾斯基三角形不递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8448908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com