在给定圆心(x,y)和半径r的情况下,如何遍历圆中的每个整数点



我尝试了以下r=10的代码,打印语句运行了12次,而不是我预期的20次,因为圆的直径与中心对齐。

public void testPoints(int x, int y, int r){
for(int i = 0; i < 360; i++){
if((int) Math.round(x+r*Math.cos(i)) == x){
System.out.println("Hi");
}
}
}

使用内置方法转换为弧度。

public void testPoints(int x, int y, int r){
for(int i = 0; i < 360; i++){
if(Math.round(x+r*Math.cos(Math.toRadians(i))) == x){
System.out.println("Hi");
}
}
}

或者从Radians开始

public static void testPoints(int x, int y, int r){
double maxAngle = 2*Math.PI;
double increment = maxAngle/360.;
for(double i = 0; i < maxAngle; i += increment){
if(Math.round(x+r*Math.cos(i)) == x){
System.out.println("Hi");
}
}
}

这里遗漏的是,函数希望角度是弧度,而不是度。要解决这个问题,只需将角度(以度为单位(转换为弧度即可。你可以通过使用这个来实现这一点:

if ((int) Math.round(x+r*Math.cos((i*Math.PI)/180)) == x){
System.out.println("Hi");
}

最新更新