我必须创建两种方法,一种用于顺时针旋转,另一种用于逆时针旋转

I have to create a two methods one for a clockwise rotation and the other anticlockwise

我有两种方法,一种是取用户输入的点,然后计算顺时针旋转 90 度,而另一种方法,完全相同,只是逆时针旋转 90 度。我已经尝试过了,但我得到了错误的结果,关于解决方法的任何建议,

private static String Clockwise(int Amount, int[] x, int[] y) {
        String message = "";
        int[] tempX = x;
        int[] tempY = y;

        for (int count = 0; count <= Amount; count++) {//amount of times
            message = "\n";
            for (int index = 0; index < pointer; index++) {//go through array
                tempX[index] = tempX[index] * -1;//multiply X
                tempY[index] = tempY[index] * 1;//multiply Y

                message += ("(" + y[index] + "," + x[index] + ")\n");//output
            }//end for  
        }//end outerfor
        return message;
    }//end clockwise

    private static String AntiClockwise(int Amount, int[] x, int[] y) {
        String message = "";
        int[] tempX = x;
        int[] tempY = y;
        for (int count = 0; count <= Amount; count++) {//amount of times
            message = "\n";
            for (int index = 0; index < pointer; index++) {//go through for loop
                tempX[index] = tempX[index] * 1;//multiply X
                tempY[index] = tempY[index] * -1;//multiply Y
                message += ("(" + tempY[index] + "," + tempX[index] + ")\n");//create message
            }//end for  
        }//end outerfor

        return message;
    }//end anticlockwise

绕原点逆时针旋转一个通用角度,公式为:

x_new =  cos(theta)*x - sin(theta)*y
y_new =  sin(theta)*x + cos(theta)*y

所以,如果你想旋转 90 度的倍数,你可以简单地使用:

double theta = Math.toRadians(90 * N);

并将其代入公式。这意味着您不需要循环旋转 N 次 - 只需旋转一次实际角度。


但是,如果您想每次旋转 90 度,只需代入 cos(90 deg) 和 sin(90 deg) 的值(逆时针旋转):

x_new = cos(90 deg)*x - sin(90 deg)*y = 0*x - 1*y = -y
y_new = sin(90 deg)*x + cos(90 deg)*y = 1*x + 0*y =  x

因此:

x_new = -y
y_new = x

这样做有好处,因为像这样的几个作业比做完整的数学运算要快得多。

注意要注意不要写:

x = -y;
y = x;

因为这些语句中的第二个使用了第一个的结果。您需要将原始 x 存储在临时变量中才能正确执行此操作。