java定义一个分数类fraction
时间: 2023-04-23 20:06:01 浏览: 190
设计一个表示分数的类Fraction。这个类用两个int类型的变量分别表示分子和分母。
5星 · 资源好评率100%
分数类fraction的定义如下:
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;
}
// 将分数转换为小数
public double toDecimal() {
return (double) numerator / denominator;
}
// 分数相加
public Fraction add(Fraction f) {
int newNumerator = numerator * f.denominator + f.numerator * denominator;
int newDenominator = denominator * f.denominator;
return new Fraction(newNumerator, newDenominator);
}
// 分数相减
public Fraction subtract(Fraction f) {
int newNumerator = numerator * f.denominator - f.numerator * denominator;
int newDenominator = denominator * f.denominator;
return new Fraction(newNumerator, newDenominator);
}
// 分数相乘
public Fraction multiply(Fraction f) {
int newNumerator = numerator * f.numerator;
int newDenominator = denominator * f.denominator;
return new Fraction(newNumerator, newDenominator);
}
// 分数相除
public Fraction divide(Fraction f) {
int newNumerator = numerator * f.denominator;
int newDenominator = denominator * f.numerator;
return new Fraction(newNumerator, newDenominator);
}
// 分数的字符串表示
public String toString() {
return numerator + "/" + denominator;
}
}
阅读全文