基于坐标的时钟上的时间位置

2024-09-30 01:24:59 发布

您现在位置:Python中文网/ 问答频道 /正文

基于x和y坐标,我需要实现一个函数

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

以获得时钟上的大致时间。粗略时间是指时钟上的整小时时间。所以在这种情况下,1点,2点,等等。。。如果坐标在半径之外,函数应该返回-1。在

或者更形象化一点:想象一下第二部饥饿游戏电影/书。你有12个不同的区域,像一个时钟一样排列。在函数中输入贡品的坐标,以及竞技场的半径,作为回报,你希望得到贡品当前所在的区域。在

所以我设法弄明白了如何检查,位置是否在时钟上

^{pr2}$

另外,我有一个小片段计算了扇区:

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

但我一直在想一种方法,如何检查给定坐标在哪个扇区。在


Tags: 函数区域new时间半径math时钟int
2条回答

我建议使用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.

使用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

相关问题 更多 >

    热门问题