Java分数运算代码错误排查:结果与预期不符求助
Java分数运算结果异常问题排查
错误根源
你的代码最后一步出现负数结果,核心有两个问题:
- int类型溢出:Java的int最大仅能存储
2147483647,但你每次运算后没有化简分子分母,导致数值持续膨胀,最终超出int范围,触发溢出变成负数。 - 未更新运算后的化简值:你只是输出了化简后的分数,但
numerator1和denominator1一直保留着运算后的原始大数——比如第一次乘法后,你输出858/71,但实际后续运算用的是未化简的5148/426,数值直接翻了6倍,一步步累积后直接撑爆int。
验证过程
拿最后一次运算举例:
第五次运算后,你代码里的numerator1是6736608,denominator1是133071750(未化简的大数),而非输出的374256/7392875。第六次做加法时,分母计算133071750*92=12242601000,这个数远大于int最大值,直接溢出成负数,导致最终结果异常。
修复方案
关键改动点
- 把分子分母的类型从
int改成long,扩大存储范围; - 每次运算后,将
numerator1和denominator1更新为化简后的数值,避免无效的数值膨胀; - 优化最大公约数(gcd)的计算,用更高效的欧几里得算法替代遍历。
修复后的完整代码
import java.util.*; import java.io.*; class Fraction { private long num; private long den; Fraction(long a, long b) { // 保证分母为正,避免符号混乱 if (b < 0) { a = -a; b = -b; } long g = gcd(Math.abs(a), Math.abs(b)); this.num = a / g; this.den = b / g; } public long getNum() { return num; } public long getDen() { return den; } // 欧几里得算法求最大公约数 public static long gcd(long a, long b) { while (b != 0) { long temp = b; b = a % b; a = temp; } return a; } @Override public String toString() { return num + "/" + den; } } class Solution { public static void main(String args[]) { Scanner sc = new Scanner(System.in); long numerator1 = sc.nextLong(); long denominator1 = sc.nextLong(); int query = sc.nextInt(); for (int i = 0; i < query; i++) { int option = sc.nextInt(); long numerator2 = sc.nextLong(); long denominator2 = sc.nextLong(); Fraction result; if (option == 1) { // 分数加法公式:a/b + c/d = (ad + bc)/bd long newNum = numerator1 * denominator2 + numerator2 * denominator1; long newDen = denominator1 * denominator2; result = new Fraction(newNum, newDen); } else if (option == 2) { // 分数乘法公式:a/b * c/d = ac/bd long newNum = numerator1 * numerator2; long newDen = denominator1 * denominator2; result = new Fraction(newNum, newDen); } else { // 无效选项,保留原分数 result = new Fraction(numerator1, denominator1); } // 更新为化简后的分数,用于下一次运算 numerator1 = result.getNum(); denominator1 = result.getDen(); System.out.println(result); } } }
效果验证
运行修复后的代码,输入给定的测试用例,输出结果将完全匹配预期:
858/71 10396/355 20792/18105 93564/295715 374256/7392875 115753177/680144500
内容的提问来源于stack exchange,提问作者Ishani
相关产品推荐
相关产品推荐

