Java递归参数

问题描述 投票:2回答:1

我坚持做作业;有没有人有想法?

任务:实现一个盒装的递归方法(double [] center,double radius),它绘制如下图:

enter image description here

(外部正方形是图像边缘。)阵列中心包含所有正方形中心的x坐标和y坐标,而半径是正方形长度的一半。内部正方形始终旋转45°。当半径小于一个像素时,该方法应停止绘制。

给出了其他方法。这个绘制了一个由双角度旋转的正方形:

private static void squareRotated(double[] center, double radius, double angle) {
        double[] upperLeft = {-radius, radius};
        double[] upperRight = {radius, radius};
        double[] lowerLeft = {-radius, -radius};
        double[] lowerRight = {radius, -radius};


        double[] rotUpperLeft = rotatePoint(upperLeft,angle);
        double[] rotUpperRight = rotatePoint(upperRight,angle);
        double[] rotLowerLeft = rotatePoint(lowerLeft,angle);
        double[] rotLowerRight = rotatePoint(lowerRight,angle);


        StdDraw.polygon(new double[]{rotUpperLeft[0]+center[0],rotUpperRight[0]+center[0],
                        rotLowerRight[0]+center[0],rotLowerLeft[0]+center[0]},
                        new double[]{rotUpperLeft[1]+center[1],rotUpperRight[1]+center[1],
                        rotLowerRight[1]+center[1],rotLowerLeft[1]+center[1]});
    }

这个以双角度旋转一个点:

private static double[] rotatePoint(double[] point, double angle) {
        double[] result = new double[2];
        result[0] = point[0]*Math.cos(angle) - point[1]*Math.sin(angle);
        result[1] = point[0]*Math.sin(angle) + point[1]*Math.cos(angle);
        return result;
    }
}

这是我的代码:

private static double angle = 0;

    private static void boxed(double[] center, double radius) {
        if (radius > (double) 1/512) {
            squareRotated(center, radius, angle);
            angle += Math.PI/4;
            boxed(center, Math.sqrt(radius*radius + radius*radius)/2);
        }
    }

它有效,但有没有办法可以避免私人静态双角?我不允许在方法中添加第三个参数,我必须通过递归来解决它。

java function recursion graphic
1个回答
1
投票

这里的常规技术是使用一个public方法公开API,然后调用private方法实际执行递归过程,将初始条件传递给它。

// The private one that actually does the recursive process.
private static void boxed(double[] center, double radius, double angle) {
    if (radius > 1.0 / 512.0) {
        squareRotated(center, radius, angle);
        angle += Math.PI / 4.0;
        boxed(center, Math.sqrt(radius * radius + radius * radius) / 2.0, angle);
    }

}

// The public one to provide the API.
public static void boxed(double[] center, double radius) {
    boxed(center, radius, 0.0);
}

注意:我没有检查过这段代码 - 这只是为了演示这种技术。

© www.soinside.com 2019 - 2024. All rights reserved.