Java:以度为单位计算两点之间的角度 [英] Java: Calculating the angle between two points in degrees

查看:1514
本文介绍了Java:以度为单位计算两点之间的角度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为自己的Point类计算两点之间的角度,点a应为中心点。



方法:

  public float getAngle(Point target){
return(float)Math.toDegrees(Math.atan2(target.x - x,target) .y - y));
}

测试1://返回45

 点a =新点(0,0); 
System.out.println(a.getAngle(new Point(1,1)));

测试2://返回-90,预期:270

 点a =新点(0,0); 
System.out.println(a.getAngle(new Point(-1,0)));

如何将返回的结果转换为0到359之间的数字?

解决方案

您可以添加以下内容:

  public float getAngle(Point target){
float angle =(float)Math.toDegrees(Math.atan2(target.y -y,target.x-x));

if(angle< 0){
angle + = 360;
}

返回角度;
}

顺便说一句,为什么你不想在这里使用双倍? / p>

I need to calculate the angle in degrees between two points for my own Point class, Point a shall be the center point.

Method:

public float getAngle(Point target) {
    return (float) Math.toDegrees(Math.atan2(target.x - x, target.y - y));
}

Test 1: // returns 45

Point a = new Point(0, 0);
    System.out.println(a.getAngle(new Point(1, 1)));

Test 2: // returns -90, expected: 270

Point a = new Point(0, 0);
    System.out.println(a.getAngle(new Point(-1, 0)));

How can i convert the returned result into a number between 0 and 359?

解决方案

you could add the following:

public float getAngle(Point target) {
    float angle = (float) Math.toDegrees(Math.atan2(target.y - y, target.x - x));

    if(angle < 0){
        angle += 360;
    }

    return angle;
}

by the way, why do you want to not use a double here?

这篇关于Java:以度为单位计算两点之间的角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆