我有以下代码,并且您可以看到,每次执行pencil.forward();时,我将相同的值除以3,但是当两边看起来不相等时。码:

import gpdraw.*;

public class buildShape {
public SketchPad paper = new SketchPad(500,500);
public DrawingTool pencil = new DrawingTool(paper);

public void drawKochCurve(int level, double initialSize){
    if (level < 1){
        pencil.forward(initialSize);
    } else {
        drawKochCurve(level - 1, initialSize);
        pencil.forward(initialSize / 3);
        pencil.turnLeft(60);
        pencil.forward(initialSize / 3);
        pencil.turnRight(120);
        pencil.forward(initialSize / 3);
        pencil.turnLeft(60);
        pencil.forward(initialSize / 3);
    }
  }
}


主要:

public class Main {
public static void main(String[] args){
    buildShape myKoch = new buildShape();
    myKoch.drawKochCurve(1,90);
  }
}

最佳答案

您的递归不充分。您需要为每个线段递归调用绘制曲线,否则不会创建分形曲线。

更改为:

} else {
    drawKochCurve(level - 1, initialSize / 3);
    // pencil.forward(initialSize / 3);
    pencil.turnLeft(60);
    drawKochCurve(level - 1, initialSize / 3);
    // pencil.forward(initialSize / 3);
    pencil.turnRight(120);
    drawKochCurve(level - 1, initialSize / 3);
    // pencil.forward(initialSize / 3);
    pencil.turnLeft(60);
    drawKochCurve(level - 1, initialSize / 3);
    // pencil.forward(initialSize / 3);
}

10-08 01:19