根据坐标在时钟上定位为时间

Position as time on a clock based on the coordinates

基于x和y坐标,我需要实现这样的功能

int getArea(double xcoord, double ycoord , double radius)

获取时钟的粗略时间。粗略时间是指时钟上的整点时间。所以在这种情况下,1 点钟、2 点钟等......如果坐标在半径之外,函数应该 return -1.

或者更生动:想象一下第二个饥饿游戏 movie/book。你有 12 个不同的区域,像时钟一样排序。然后在函数中输入贡品的坐标以及竞技场的半径,然后在 return 中输入贡品当前所在的区域。

所以我设法弄清楚了如何检查位置是否在时钟上

if(Math.pow(x,2) + Math.pow(y,2) < Math.pow(radius,2))

此外,我有一个计算扇区的小程序:

int sectors = 12;
double angle = 2*Math.PI/sectors;
double x_sectors[] = new double[sectors];
double y_sectors[] = new double[sectors];
for(int i = 0; i<sectors; i++){
    x_sectors[i] = Math.cos(i*angle)*radius;
    y_sectors[i] = Math.sin(i*angle)*radius;
}

但我一直坚持使用一种方法来检查给定坐标在哪个扇区。

使用Math.hypot()Math.atan2()方法根据给定的x和y进行极坐标计算:

if (Math.hypot(x, y) > radius)  
   return -1;                      // out of the circle
double theta = Math.atan2(x, y);
if (theta < 0)
   theta += Math.PI * 2d;
int sector = (int)(theta / Math.PI / 2d * 12d) + 1; // number of one of 12 sectors enumerated from 1

我推荐使用Math.atan2方法,并改变其角度范围:

int getArea(double xcoord, double ycoord , double radius) {
    if(xcoord*xcoord + ycoord*ycoord > radius*radius)
        return -1;
    double angle = Math.PI/2 - Math.atan2(ycoord, xcoord); // Need to suptract the angle from Pi/2 because we want 0 rad to be at +y axis instead of +x axis
    if(angle < 0) // Math.atan2 gives angle in range -Pi/2 to Pi/2 so need to shift it to range 0 to 2*Pi
        angle = 2*Math.PI + angle;
    int segments = 12;
    double angle_one_segment = 2*Math.PI/segments;
    return 1 + (int)(angle/angle_one_segment); // From 12 o'clock to 1 o'clock it's first sector (exactly 12 belongs to 1st sector) and so on. If point (x, y) lies exactly at the boundary between 2 sectors it belongs to the higher one
}

See it run with some testcases on ideone.