英文:
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 < 360; i++){
if((int) Math.round(x+r*Math.cos(i)) == x){
System.out.println("Hi");
}
}
}
答案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 < 360; i++){
if(Math.round(x+r*Math.cos(Math.toRadians(i))) == x){
System.out.println("Hi");
}
}
}
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 < maxAngle; i += increment){
if(Math.round(x+r*Math.cos(i)) == x){
System.out.println("Hi");
}
}
}
</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("Hi");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论