问题描述
所以我试图使用点 rsin(theta) 和 rcos(theta) 公式来制作一个六边形,但公式中似乎有一些错误。当把它写在纸上时,公式是有效的,但感觉我忽略了一些东西......
public static void drawHexagon(double len,double xc,double yc,int angle)
{
if(angle <= -360)
angle = 0;
double rotAngX = (len*Math.cos(angle));
double rotAngY = (len*Math.sin(angle));
//System.out.println(rotAngX + " " + rotAngY + " " + Math.cos(-30));
/*double [] x = {(xc - len*(Math.sqrt(3)/2.0)),xc,xc + len*(Math.sqrt(3)/2.0),xc - len*(Math.sqrt(3)/2.0)};
double [] y = {yc + len/2.0,yc + len,yc + len/2.0,yc - len/2.0,yc - len,yc - len/2.0};*/
double[] x = new double[6];
double[] y = new double[6];
int[] angles = { 150,90,30,330,270,210 };
for(int i = 0; i < 6; i++) {
x[i] = xc + (len*Math.cos(angles[i]));
y[i] = yc + (len*Math.sin(angles[i]));
}
printPoints(x,y);
stddraw.setPenColor(Color.CYAN);
stddraw.filledpolygon(x,y);
stddraw.setPenColor(Color.PINK);
stddraw.polygon(x,y);
}
注释掉的部分有效,但我正在尝试旋转它们,因此在 for 循环中将角度参数添加到angle[i]。我在 for 循环中做错了什么?
这是代码的结果。六边形但不是真的:
解决方法
Math.sin 的 Javadoc 说:
public static double sin(double a)
返回一个角度的三角正弦值。 [...]
参数:
a - 一个角度,以弧度为单位。
您的代码以度数而不是 radians 传递角度。
您可以先转换角度:
Math.sin(Math.toRadians(30))
或直接以弧度指定角度:
Math.sin(Math.PI / 6);
,
我不确定您要做什么,但是是这样吗?:
public static void drawHexagon(double len,double xc,double yc,int angle)
{
double[] x = new double[6];
double[] y = new double[6];
x[0] = len*Math.cos(3.14*angle/180.0);
y[0] = len*Math.sin(3.14*angle/180.0);
double cos_60;
double sin_60;
cos_60 = 1.0/2.0;
sin_60 = Math.sqrt(3.0)/2.0;
for(int i = 1; i < 6; i++) {
x[i] = xc + cos_60*x[i-1] - sin_60*y[i-1];
y[i] = yc + sin_60*x[i-1] + cos_60*y[i-1];
}
printPoints(x,y);
StdDraw.setPenColor(Color.CYAN);
StdDraw.filledPolygon(x,y);
StdDraw.setPenColor(Color.PINK);
StdDraw.polygon(x,y);
}