java创建一个分数类
时间: 2023-10-02 18:13:57 浏览: 95
好的,关于 Java 创建一个分数类的问题,我可以为您提供以下代码:
```
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 Fraction add(Fraction other) {
int newDenominator = lcm(denominator, other.denominator);
int newNumerator = numerator * (newDenominator / denominator) + other.numerator * (newDenominator / other.denominator);
return new Fraction(newNumerator, newDenominator).simplify();
}
public Fraction subtract(Fraction other) {
int newDenominator = lcm(denominator, other.denominator);
int newNumerator = numerator * (newDenominator / denominator) - other.numerator * (newDenominator / other.denominator);
return new Fraction(newNumerator, newDenominator).simplify();
}
public Fraction multiply(Fraction other) {
int newNumerator = numerator * other.numerator;
int newDenominator = denominator * other.denominator;
return new Fraction(newNumerator, newDenominator).simplify();
}
public Fraction divide(Fraction other) {
int newNumerator = numerator * other.denominator;
int newDenominator = denominator * other.numerator;
return new Fraction(newNumerator, newDenominator).simplify();
}
public boolean equals(Fraction other) {
return numerator * other.denominator == denominator * other.numerator;
}
@Override
public String toString() {
return numerator + "/" + denominator;
}
private int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
private int lcm(int a, int b) {
return a * b / gcd(a, b);
}
private Fraction simplify() {
int gcd = gcd(numerator, denominator);
if (gcd != 1) {
return new Fraction(numerator / gcd, denominator / gcd);
} else {
return this;
}
}
}
```
这是一个基本的分数类,其中包含四则运算和一些基本操作。您可以在此基础上进行扩展和优化。希望能对您有所帮助。
阅读全文