首页 > 解决方案 > 如何通过给定中心(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");
        }
    }
}

标签: javamath

解决方案


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

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

推荐阅读