You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何切换角度输出格式?Java向量角度单位转换技术问询

解决方案:实现角度单位切换与统计

核心思路

要实现角度单位(度/弧度)的切换与统计,需要在MyVector类中添加全局单位状态、切换计数器,并让angle方法根据当前单位返回对应数值。以下是具体实现步骤:


1. 定义角度单位枚举

先创建枚举类明确单位类型,避免使用模糊的字符串或数字:

public enum AngleUnit {
    DEGREE, RADIAN
}

2. 修改MyVector类

添加静态变量存储当前单位、切换计数器,同时实现切换方法和适配单位的angle计算:

public class MyVector {
    private double x;
    private double y;
    // 全局角度单位,初始为度
    private static AngleUnit currentUnit = AngleUnit.DEGREE;
    // 单位切换次数计数器
    private static int switchCount = 0;

    public MyVector(double x, double y) {
        this.x = x;
        this.y = y;
    }

    // 切换角度单位
    public static void switchAngleUnit() {
        currentUnit = (currentUnit == AngleUnit.DEGREE) ? AngleUnit.RADIAN : AngleUnit.DEGREE;
        switchCount++;
    }

    // 获取当前单位
    public static AngleUnit getCurrentAngleUnit() {
        return currentUnit;
    }

    // 获取切换次数
    public static int getSwitchCount() {
        return switchCount;
    }

    // 计算两向量夹角(根据当前单位返回结果)
    public double angle(MyVector other) {
        // 先计算弧度值(Java Math类默认使用弧度)
        double dotProduct = this.x * other.x + this.y * other.y;
        double magnitude1 = Math.sqrt(this.x * this.x + this.y * this.y);
        double magnitude2 = Math.sqrt(other.x * other.x + other.y * other.y);
        double radians = Math.acos(dotProduct / (magnitude1 * magnitude2));

        // 根据当前单位转换结果
        return currentUnit == AngleUnit.DEGREE ? Math.toDegrees(radians) : radians;
    }
}

3. 修正测试方法(避免浮点数直接比较)

浮点数计算存在精度误差,不能直接用==判断,需设置误差范围:

public static boolean isUsingDegree(String[] args) {
    MyVector vec1 = new MyVector(2, 3);
    MyVector vec2 = new MyVector(-1, 4);
    double expectedDegree = 47.7263;
    double actual = vec1.angle(vec2);
    // 允许±0.0001的误差
    return Math.abs(actual - expectedDegree) < 1e-4;
}

4. 测试切换逻辑

通过以下代码验证单位切换和计数器功能:

public static void main(String[] args) {
    // 初始状态:单位为度,切换次数0
    System.out.println("初始是否为度:" + isUsingDegree(args)); // 输出true
    System.out.println("切换次数:" + MyVector.getSwitchCount()); // 输出0

    // 切换到弧度
    MyVector.switchAngleUnit();
    System.out.println("切换后是否为度:" + isUsingDegree(args)); // 输出false
    System.out.println("切换次数:" + MyVector.getSwitchCount()); // 输出1

    // 切换回度
    MyVector.switchAngleUnit();
    System.out.println("再次切换后是否为度:" + isUsingDegree(args)); // 输出true
    System.out.println("切换次数:" + MyVector.getSwitchCount()); // 输出2
}

关键注意点

  • 全局单位用静态变量:确保所有MyVector实例共用同一单位设置,符合常规使用逻辑
  • 计数器用静态变量:统计全局的切换次数,每次调用switchAngleUnit自动递增
  • 浮点数比较必须用误差范围:直接==会因计算精度问题导致判断错误

内容的提问来源于stack exchange,提问作者user20146539

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 00:55:54