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

Java两数大小及倍数关系校验实现与现有代码问题排查

问题排查
  • 逻辑运算符误用:所有分支的判断条件错误使用||(或)运算符,只要任意一个子条件满足就会触发当前分支,而需求要求同时满足「大小关系成立」+「倍数在指定区间」两个要求,应该改用&&(与)运算符。
  • 倍数区间逻辑错误:比如判断a略大于b的分支中,写的a/b<1实际代表a<b,完全和需求相反,1~2倍区间对应的应该是a/b > 1 && a/b <2。
  • 浮点数相等判断风险:直接用a==b判断浮点数相等存在精度误差问题,比如0.1+0.2的结果不等于0.3,应该用两数差值的绝对值小于极小阈值(比如1e-9)来判断相等。
  • 除零异常风险:代码没有判断除数是否为0,当b为0时执行a/b、a为0时执行b/a都会直接抛出异常。
  • 代码冗余严重:a大于b和b大于a的逻辑完全一致,重复写了两遍相同的判断逻辑,后续维护难度高。
优化实现方案

优化后代码消除了重复逻辑,增加了边界场景处理,运行效率和可维护性更高:

import java.util.Scanner;

public class Main {
    // 浮点数相等判断的精度阈值
    private static final double EPSILON = 1e-9;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("请输入a的值:");
        double a = input.nextDouble();
        System.out.println("请输入b的值:");
        double b = input.nextDouble();

        // 判断两数相等
        if (Math.abs(a - b) < EPSILON) {
            System.out.println("a等于b");
            return;
        }

        // 统一识别较大值、较小值和对应名称
        double larger, smaller;
        String largerName;
        if (a > b) {
            larger = a;
            smaller = b;
            largerName = "a";
        } else {
            larger = b;
            smaller = a;
            largerName = "b";
        }
        String smallerName = largerName.equals("a") ? "b" : "a";

        // 处理较小值为0的边界场景,此时倍数无穷大属于大很多
        if (Math.abs(smaller) < EPSILON) {
            System.out.printf("%s比%s大很多%n", largerName, smallerName);
            return;
        }

        // 计算绝对值的倍数,兼容正负值场景
        double ratio = Math.abs(larger) / Math.abs(smaller);
        if (ratio < 2) {
            System.out.printf("%s比%s略大%n", largerName, smallerName);
        } else if (ratio < 3) {
            System.out.printf("%s比%s大2x%n", largerName, smallerName);
        } else if (ratio < 4) {
            System.out.printf("%s比%s大3x%n", largerName, smallerName);
        } else if (ratio < 5) {
            System.out.printf("%s比%s大4x%n", largerName, smallerName);
        } else if (ratio < 6) {
            System.out.printf("%s比%s大5x%n", largerName, smallerName);
        } else {
            System.out.printf("%s比%s大很多%n", largerName, smallerName);
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:36:02