写一个java有理数rational类,分子为整型p,分母为整型q,构造方法Rational(int p,int q),定义其加减乘除及toString()方法
时间: 2024-12-16 16:24:45 浏览: 4
在Java中,我们可以创建一个名为`Rational`的有理数类,它包含两个整型成员变量`public int numerator`表示分子,`public int denominator`表示分母。下面是一个简单的实现:
```java
public class Rational {
private int numerator;
private int denominator;
// 构造函数,接收分子和分母作为参数
public Rational(int p, int q) {
if (q != 0) {
this.numerator = p;
this.denominator = q;
} else {
throw new IllegalArgumentException("Denominator cannot be zero");
}
}
// 加法方法
public Rational add(Rational other) {
int newNum = numerator * other.denominator + other.numerator * denominator;
int newDen = denominator * other.denominator;
return new Rational(newNum, newDen);
}
// 减法方法
public Rational subtract(Rational other) {
int newNum = numerator * other.denominator - other.numerator * denominator;
return new Rational(newNum, denominator * other.denominator);
}
// 乘法方法
public Rational multiply(Rational other) {
return new Rational(numerator * other.numerator, denominator * other.denominator);
}
// 除法方法,需要检查除数是否为零
public Rational divide(Rational other) {
if (other.denominator != 0) {
return new Rational(numerator * other.denominator, denominator * other.numerator);
} else {
throw new ArithmeticException("Cannot divide by zero");
}
}
// toString()方法,用于将有理数转换为字符串展示
@Override
public String toString() {
if (denominator > 0) {
return numerator + "/" + denominator;
} else {
return numerator + " / (-" + (-denominator) + ")";
}
}
}
```
在这个类中,我们提供了基本的数学运算方法以及`toString()`方法,以方便打印有理数。注意,这里假设了除数不为零,实际应用中可能需要添加异常处理来处理这种边界情况。
阅读全文