java实现假分数加减乘除运算
时间: 2023-11-18 11:48:24 浏览: 137
java 实现加减乘除
以下是java实现假分数加减乘除运算的示例代码:
假分数类Fraction:
```java
public class Fraction {
private int numerator; // 分子
private int denominator; // 分母
// 构造函数
public Fraction(int numerator, int denominator) {
if (denominator == 0) {
throw new IllegalArgumentException("分母不能为0");
}
int gcd = gcd(numerator, denominator);
this.numerator = numerator / gcd;
this.denominator = denominator / gcd;
if (this.denominator < 0) { // 统一分母为正数
this.numerator = -this.numerator;
this.denominator = -this.denominator;
}
}
// 加法
public Fraction add(Fraction f) {
int newNumerator = this.numerator * f.denominator + this.denominator * f.numerator;
int newDenominator = this.denominator * f.denominator;
return new Fraction(newNumerator, newDenominator);
}
// 减法
public Fraction subtract(Fraction f) {
int newNumerator = this.numerator * f.denominator - this.denominator * f.numerator;
int newDenominator = this.denominator * f.denominator;
return new Fraction(newNumerator, newDenominator);
}
// 乘法
public Fraction multiply(Fraction f) {
int newNumerator = this.numerator * f.numerator;
int newDenominator = this.denominator * f.denominator;
return new Fraction(newNumerator, newDenominator);
}
// 除法
public Fraction divide(Fraction f) {
if (f.numerator == 0) {
throw new IllegalArgumentException("除数不能为0");
}
int newNumerator = this.numerator * f.denominator;
int newDenominator = this.denominator * f.numerator;
return new Fraction(newNumerator, newDenominator);
}
// 获取分子
public int getNumerator() {
return numerator;
}
// 获取分母
public int getDenominator() {
return denominator;
}
// 判断是否为整数
public boolean isInteger() {
return numerator % denominator == 0;
}
// 转化为整数
public int toInteger() {
return numerator / denominator;
}
// 转化为字符串
public String toString() {
if (isInteger()) {
return String.valueOf(toInteger());
} else {
return String.format("%d/%d", numerator, denominator);
}
}
// 获取最大公约数
private int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
}
```
测试代码:
```java
public class Main {
public static void main(String[] args) {
Fraction f1 = new Fraction(3, 4);
Fraction f2 = new Fraction(1, 2);
System.out.println(f1.add(f2)); // 输出5/4
System.out.println(f1.subtract(f2)); // 输出1/4
System.out.println(f1.multiply(f2)); // 输出3/8
System.out.println(f1.divide(f2)); // 输出3/2
}
}
```
阅读全文