java中多分数类Fraction的实现,private static void norm(Fraction a,Fraction b)通分及加减乘除运算
时间: 2024-06-13 18:07:01 浏览: 131
以下是Java中多分数类Fraction的实现,包括通分及加减乘除运算的示例:
```java
public class Fraction {
private int numerator; // 分子
private int denominator; // 分母
// 构造函数
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
// 获取分子
public int getNumerator() {
return numerator;
}
// 获取分母
public int getDenominator() {
return denominator;
}
// 通分
private static void norm(Fraction a, Fraction b) {
int lcm = lcm(a.denominator, b.denominator);
a.numerator *= lcm / a.denominator;
b.numerator *= lcm / b.denominator;
a.denominator = lcm;
b.denominator = lcm;
}
// 加法
public static Fraction add(Fraction a, Fraction b) {
Fraction res = new Fraction(0, 1);
norm(a, b);
res.numerator = a.numerator + b.numerator;
res.denominator = a.denominator;
return res;
}
// 减法
public static Fraction subtract(Fraction a, Fraction b) {
Fraction res = new Fraction(0, 1);
norm(a, b);
res.numerator = a.numerator - b.numerator;
res.denominator = a.denominator;
return res;
}
// 乘法
public static Fraction multiply(Fraction a, Fraction b) {
Fraction res = new Fraction(0, 1);
res.numerator = a.numerator * b.numerator;
res.denominator = a.denominator * b.denominator;
return res;
}
// 除法
public static Fraction divide(Fraction a, Fraction b) {
Fraction res = new Fraction(0, 1);
res.numerator = a.numerator * b.denominator;
res.denominator = a.denominator * b.numerator;
return res;
}
// 求最大公约数
private static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
// 求最小公倍数
private static int lcm(int a, int b) {
return a * b / gcd(a, b);
}
}
```
示例:
```java
Fraction f1 = new Fraction(1, 3);
Fraction f2 = new Fraction(2, 5);
// 通分
Fraction.norm(f1, f2);
// 加法
Fraction res1 = Fraction.add(f1, f2);
System.out.println(res1.getNumerator() + "/" + res1.getDenominator()); // 输出:11/15
// 减法
Fraction res2 = Fraction.subtract(f1, f2);
System.out.println(res2.getNumerator() + "/" + res2.getDenominator()); // 输出:-1/15
// 乘法
Fraction res3 = Fraction.multiply(f1, f2);
System.out.println(res3.getNumerator() + "/" + res3.getDenominator()); // 输出:2/15
// 除法
Fraction res4 = Fraction.divide(f1, f2);
System.out.println(res4.getNumerator() + "/" + res4.getDenominator()); // 输出:5/6
```
阅读全文