java - 如何通过给定中心(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");
}
}
}
或者从循环中的弧度开始
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");
}
}
}
推荐阅读
- docker - 大厅 ci 在哪里创建容器来运行任务?如何进入这些容器中的任何一个?
- python - cv2.calibrateCamera 成功后如何获得好的 cv2.stereoCalibrate
- ionic-framework - Ionic 3 图像未显示在设备上
- hibernate - 在多线程环境中与 Hibernate 会话进行交互的合适方式
- c# - 如何使用 SSIS 脚本任务删除 Excel 目标中的第二行?SQL Server 2012
- python - tkinter 顶级小部件的协议有哪些
- swift - 如何在 Promisekit 循环中使用 when 函数
- linux - scp 从 Linux 到 Windows: 'C:\Program' 无法识别错误
- json - 发送标志而不是基于 json 的字母
- entity-framework - MVC 业务逻辑 + DAL + 映射 ViewModel 和 EF 模型