java实现假分数加减乘除运算
时间: 2023-11-18 10:56:12 浏览: 125
下面是Java实现假分数加减乘除运算的示例代码:
```java
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 Fraction toImproperFraction() {
int newNumerator = numerator + denominator * (numerator < 0 ? -1 : 1);
return new Fraction(newNumerator, denominator);
}
// 加法
public static Fraction add(Fraction f1, Fraction f2) {
int newNumerator = f1.getNumerator() * f2.getDenominator() + f2.getNumerator() * f1.getDenominator();
int newDenominator = f1.getDenominator() * f2.getDenominator();
return new Fraction(newNumerator, newDenominator).toImproperFraction();
}
// 减法
public static Fraction subtract(Fraction f1, Fraction f2) {
int newNumerator = f1.getNumerator() * f2.getDenominator() - f2.getNumerator() * f1.getDenominator();
int newDenominator = f1.getDenominator() * f2.getDenominator();
return new Fraction(newNumerator, newDenominator).toImproperFraction();
}
// 乘法
public static Fraction multiply(Fraction f1, Fraction f2) {
int newNumerator = f1.getNumerator() * f2.getNumerator();
int newDenominator = f1.getDenominator() * f2.getDenominator();
return new Fraction(newNumerator, newDenominator).toImproperFraction();
}
// 除法
public static Fraction divide(Fraction f1, Fraction f2) {
int newNumerator = f1.getNumerator() * f2.getDenominator();
int newDenominator = f1.getDenominator() * f2.getNumerator();
return new Fraction(newNumerator, newDenominator).toImproperFraction();
}
// 输出假分数
public String toString() {
int integerPart = numerator / denominator;
int newNumerator = numerator % denominator;
if (newNumerator == 0) {
return String.valueOf(integerPart);
}
return integerPart + " " + newNumerator + "/" + denominator;
}
}
```
接下来是一个简单的测试:
```java
public class Main {
public static void main(String[] args) {
Fraction f1 = new Fraction(3, 4);
Fraction f2 = new Fraction(1, 2);
Fraction sum = Fraction.add(f1, f2);
Fraction difference = Fraction.subtract(f1, f2);
Fraction product = Fraction.multiply(f1, f2);
Fraction quotient = Fraction.divide(f1, f2);
System.out.println(f1 + " + " + f2 + " = " + sum);
System.out.println(f1 + " - " + f2 + " = " + difference);
System.out.println(f1 + " * " + f2 + " = " + product);
System.out.println(f1 + " / " + f2 + " = " + quotient);
}
}
```
输出结果应该为:
```
3/4 + 1/2 = 5/4
3/4 - 1/2 = 1/4
3/4 * 1/2 = 3/8
3/4 / 1/2 = 3/2
```
阅读全文