0

我有以下代码,如您所见,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);
  }
}

在此处输入图像描述

4

1 回答 1

1

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

将其更改为:

} 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);
}
于 2013-10-27T20:04:10.600 回答