当然可以,以下是整体代码形式的修复后的版本:import java.util.Scanner;class Fraction { private int numerator; // 分子 private int denominator; // 分母 // 构造方法 public Fraction(int a, int b) { if (b == 0) { System.out.println("错误,分母不能为0"); return; } numerator = a; denominator = b; yuefen(); } // 将分数转换为double public double toDouble() { return (double) numerator / denominator; } // 将自身和r的分数相加,产生一个新的Fraction的对象 public Fraction plus(Fraction r) { int newNumerator = this.numerator * r.denominator + this.denominator * r.numerator; int newDenominator = this.denominator * r.denominator; return new Fraction(newNumerator, newDenominator); } // 将自身和r的分数相乘,产生一个新的Fraction的对象 public Fraction multiply(Fraction r) { int newNumerator = this.numerator * r.numerator; int newDenominator = this.denominator * r.denominator; return new Fraction(newNumerator, newDenominator); } // 输出分数 public void print() { if (denominator == 0) { System.out.println("错误,分母不能为0"); return; } if (numerator == 0) { System.out.println(0); return; } if (denominator == 1) { System.out.println(numerator); return; } System.out.println(numerator + "/" + denominator); } // 约分和调整负号 private void yuefen() { int aa = (int) Math.abs(numerator); int ab = (int) Math.abs(denominator); if (numerator * denominator >= 0) { // 调整负号 numerator = aa; denominator = ab; } else { numerator = -aa; denominator = ab; } for (int i = ((aa < ab) ? aa : ab); i > 1; i--) { // 求最大公因数,并约分 if (numerator % i == 0 && denominator % i == 0) { numerator /= i; denominator /= i; break; } } }}public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); Fraction a = new Fraction(in.nextInt(), in.nextInt()); Fraction b = new Fraction(in.nextInt(), in.nextInt()); a.print(); b.print(); a.plus(b).print(); a.multiply(b).plus(new Fraction(5, 6)).print(); a.print(); b.print(); in.close(); }}
请尝试使用修复后的代码,再次运行测试用例。如果仍然无法通过,请将具体的出错信息告诉我,我会继续帮助您调试。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |