创建一个Fraction类执行分数运算
时间: 2024-09-19 15:12:32 浏览: 36
fraction:分数运算,可避免部分小数带来的精度问题
创建一个`Fraction`类来执行分数运算,你可以定义一个包含分子(numerator)和分母(denominator)的类,并提供加法、减法、乘法和除法的方法。下面是一个简单的实现示例:
```java
public class Fraction {
private int numerator;
private int denominator;
// 构造器
public Fraction(int numerator, int denominator) {
if (denominator == 0) {
throw new IllegalArgumentException("Denominator cannot be zero");
}
this.numerator = numerator;
this.denominator = denominator;
}
// 获取或设置分子/分母
public int getNumerator() { return numerator; }
public int getDenominator() { return denominator; }
// 设置分母为最小公倍数,避免简化后的结果不正确
private int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
// 私有方法用于简化分数
private void simplify() {
int gcdValue = gcd(numerator, denominator);
numerator /= gcdValue;
denominator /= gcdValue;
}
// 加法
public Fraction add(Fraction other) {
int sumNumerator = numerator * other.getDenominator() + other.numerator * denominator;
int sumDenominator = denominator * other.getDenominator();
simplify();
return new Fraction(sumNumerator, sumDenominator);
}
// 减法
public Fraction subtract(Fraction other) {
int differenceNumerator = numerator * other.getDenominator() - other.numerator * denominator;
int differenceDenominator = denominator * other.getDenominator();
simplify();
return new Fraction(differenceNumerator, differenceDenominator);
}
// 乘法
public Fraction multiply(Fraction other) {
int productNumerator = numerator * other.numerator;
int productDenominator = denominator * other.denominator;
simplify();
return new Fraction(productNumerator, productDenominator);
}
// 除法,注意要检查除数是否为零
public Fraction divide(Fraction other) {
if (other.denominator != 0) {
int quotientNumerator = numerator * other.denominator;
int quotientDenominator = denominator * other.numerator;
simplify();
return new Fraction(quotientNumerator, quotientDenominator);
} else {
throw new ArithmeticException("Cannot divide by zero");
}
}
@Override
public String toString() {
return numerator + "/" + denominator;
}
}
```
阅读全文