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

huangapple go评论126阅读模式
英文:

How to run through every integer point in a circle given center (x,y) and radius 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");
        }
    }
}
英文:

I tried the code below with r = 10 and the print statement ran 12 times instead of my expected 20 since the diameter of the circle aligns with the center.

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

答案1

得分: 1

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

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");
        }
    }
}

或者在循环中直接使用弧度。

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");
        }
    }
}
英文:

Use the built-in method to convert to radians.

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

Or Just start off with Radians in your loop

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

</details>



# 答案2
**得分**: 0

你错过的是,该函数要求角度以弧度而非度数表示。要修复这个问题,只需将角度从度数转换为弧度。你可以通过以下方式实现:
```java
if ((int) Math.round(x + r * Math.cos((i * Math.PI) / 180)) == x) {
    System.out.println("Hi");
}
英文:

What you missed here is that the function expects the angle to be in radians and not degrees. To fix that, simply convert the angle in degrees to radians. You can achieve that by using this:

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

huangapple
  • 本文由 发表于 2020年4月11日 00:21:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/61144393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定