使用java写出关于分式的运算代码
时间: 2023-06-11 07:04:45 浏览: 110
好的,请稍等,我帮您查找一下相关代码:
```java
public class Fraction {
private int numerator; // 分子
private int denominator; // 分母
// 构造函数
public Fraction(int numerator, int denominator) {
if (denominator == 0) {
throw new IllegalArgumentException("分母不能为0!");
} else if (denominator < 0) {
this.numerator = -numerator;
this.denominator = -denominator;
} else {
this.numerator = numerator;
this.denominator = denominator;
}
simplify();
}
// 约分函数
private void simplify() {
int gcd = gcd(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
}
// 最大公约数函数
private int gcd(int p, int q) {
if (q == 0) return p;
int r = p % q;
return gcd(q, r);
}
// 加法操作
public Fraction add(Fraction other) {
int newNumerator = numerator * other.denominator + other.numerator * denominator;
int newDenominator = denominator * other.denominator;
return new Fraction(newNumerator, newDenominator);
}
// 减法操作
public Fraction subtract(Fraction other) {
int newNumerator = numerator * other.denominator - other.numerator * denominator;
int newDenominator = denominator * other.denominator;
return new Fraction(newNumerator, newDenominator);
}
// 乘法操作
public Fraction multiply(Fraction other) {
int newNumerator = numerator * other.numerator;
int newDenominator = denominator * other.denominator;
return new Fraction(newNumerator, newDenominator);
}
// 除法操作
public Fraction divide(Fraction other) {
if (other.numerator == 0) {
throw new IllegalArgumentException("除数不能为0!");
}
int newNumerator = numerator * other.denominator;
int newDenominator = denominator * other.numerator;
return new Fraction(newNumerator, newDenominator);
}
// 打印分数
public void print() {
System.out.println(numerator + "/" + denominator);
}
}
```
以上就是使用 Java 实现的关于分式的运算代码,包括加减乘除操作以及约分等功能。请您根据需要进行调用或修改。如有其它问题,请告诉我,我会尽力帮助您。
阅读全文