用java编写代码,条件如下,Rational 有理数(分数) 1.分子 numerator,分母denominator 2.构造方法两个 3.生成getter和setter方法 4.求两个分数的和 5.toString方法,"1/2"
时间: 2024-06-06 18:08:18 浏览: 115
public class Rational {
private int numerator; // 分子
private int denominator; // 分母
public Rational(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
public Rational() {
this.numerator = 0;
this.denominator = 1;
}
public int getNumerator() {
return numerator;
}
public void setNumerator(int numerator) {
this.numerator = numerator;
}
public int getDenominator() {
return denominator;
}
public void setDenominator(int denominator) {
this.denominator = denominator;
}
public Rational add(Rational r) {
int newNumerator = numerator * r.denominator + r.numerator * denominator;
int newDenominator = denominator * r.denominator;
return new Rational(newNumerator, newDenominator);
}
@Override
public String toString() {
return numerator + "/" + denominator;
}
}
阅读全文