用java写一个有理数类,相关属性和方法要求如下图。 写一个测试类,创建两个有理数对象,输出两个有理数的加、减、乘、除结果。
时间: 2023-05-31 19:06:35 浏览: 147
有理数类:
```java
public class RationalNumber {
private int numerator; // 分子
private int denominator; // 分母
// 构造方法
public RationalNumber(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
simplify(); // 约分
}
// 加法
public RationalNumber add(RationalNumber rn) {
int lcm = lcm(denominator, rn.denominator); // 最小公倍数
int num = numerator * lcm / denominator + rn.numerator * lcm / rn.denominator;
return new RationalNumber(num, lcm);
}
// 减法
public RationalNumber subtract(RationalNumber rn) {
int lcm = lcm(denominator, rn.denominator); // 最小公倍数
int num = numerator * lcm / denominator - rn.numerator * lcm / rn.denominator;
return new RationalNumber(num, lcm);
}
// 乘法
public RationalNumber multiply(RationalNumber rn) {
return new RationalNumber(numerator * rn.numerator, denominator * rn.denominator);
}
// 除法
public RationalNumber divide(RationalNumber rn) {
return new RationalNumber(numerator * rn.denominator, denominator * rn.numerator);
}
// 约分
private void simplify() {
int gcd = gcd(numerator, denominator); // 最大公约数
numerator /= gcd;
denominator /= gcd;
if (denominator < 0) { // 分母为负数时,将分子和分母都取相反数
numerator = -numerator;
denominator = -denominator;
}
}
// 求最大公约数
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
// 求最小公倍数
private int lcm(int a, int b) {
return a * b / gcd(a, b);
}
// 转化为字符串
public String toString() {
return numerator + "/" + denominator;
}
}
```
测试类:
```java
public class TestRationalNumber {
public static void main(String[] args) {
RationalNumber rn1 = new RationalNumber(3, 5);
RationalNumber rn2 = new RationalNumber(2, 3);
// 加法
RationalNumber sum = rn1.add(rn2);
System.out.println(rn1 + " + " + rn2 + " = " + sum);
// 减法
RationalNumber diff = rn1.subtract(rn2);
System.out.println(rn1 + " - " + rn2 + " = " + diff);
// 乘法
RationalNumber product = rn1.multiply(rn2);
System.out.println(rn1 + " * " + rn2 + " = " + product);
// 除法
RationalNumber quotient = rn1.divide(rn2);
System.out.println(rn1 + " / " + rn2 + " = " + quotient);
}
}
```
输出结果:
```
3/5 + 2/3 = 19/15
3/5 - 2/3 = 1/15
3/5 * 2/3 = 2/5
3/5 / 2/3 = 9/10
```
阅读全文