我正在编写一个程序的代码,该程序在圆周上的点之间绘制线条。我使用这个等式在圆周上设置点:
x = center + r * cos(angle)
y = center + r * sin(angle)
但出于某种原因,我的观点不会在圆周上均匀分布。我无法弄清楚原因。 最终看起来像这样:
public void setPoints(){
double circumference = d*Math.PI;
int x;
int y;
int nPoints = 10; //this is a variable determined by the user
int space = (int) (circumference/nPoints);
int start=0;
System.out.println("space: " + space);
int r = 20;
int a = 506;
int b = 356;
int centerX = a;
int centerY = b;
int counter = 0;
while (counter <= nPoints) {
x = (int) (centerX + r * Math.cos(start));
y = (int) (centerY + r * Math.sin(start));
pointArray.add(new Point(x, y));
System.out.println("---"+counter+"---");
start += space;
counter++;
}
}
我做错了什么?
答案 0 :(得分:2)
更换:
int space = (int) (circumference/nPoints);
int start = 0;
使用:
double space = (2 * Math.PI) / nPoints;
double start = 0;
应该做的伎俩。为清楚起见,您应将space
重命名为angle
或其他内容。
2 * Math.PI
是一个全角度,用弧度表示。 (2 * Math.PI) / nPoints
是您需要在两点之间应用的角度。
答案 1 :(得分:2)
如果我正确地提出了您的问题,您希望沿圆周标记一定数量的点,以便它们将圆周分成相等的部分。那是对的吗?如果是这样,我建议使用角度:
public void setPoints(){
double radius = 2*Math.PI;
int r = 20;
int centerX = 506;
int centerY = 356;
int nPoints = 10; //this is a variable determined by the user
for (int i = 0; i < nPoints; i++) {
double currentAngle = i * radius / nPoints;
x = (int) (centerX + r * Math.cos(currentAngle));
y = (int) (centerY + r * Math.sin(currentAngle));
pointArray.add(new Point(x, y));
}
}