java编写代码实现假分数加减乘除运算
时间: 2024-01-15 21:14:38 浏览: 109
以下是Java代码实现假分数加减乘除运算的示例:
```java
import java.util.Scanner;
public class Fraction {
private int numerator; // 分子
private int denominator; // 分母
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
// 获取最大公约数
private int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
// 约分
private Fraction reduce() {
int gcd = gcd(numerator, denominator);
return new Fraction(numerator / gcd, denominator / gcd);
}
// 转化为假分数
private Fraction toImproperFraction() {
int newNumerator = numerator + denominator * (numerator / denominator);
return new Fraction(newNumerator, denominator);
}
// 加法
public Fraction add(Fraction other) {
int newNumerator = numerator * other.denominator + other.numerator * denominator;
int newDenominator = denominator * other.denominator;
return new Fraction(newNumerator, newDenominator).reduce();
}
// 减法
public Fraction subtract(Fraction other) {
int newNumerator = numerator * other.denominator - other.numerator * denominator;
int newDenominator = denominator * other.denominator;
return new Fraction(newNumerator, newDenominator).reduce();
}
// 乘法
public Fraction multiply(Fraction other) {
int newNumerator = numerator * other.numerator;
int newDenominator = denominator * other.denominator;
return new Fraction(newNumerator, newDenominator).reduce().toImproperFraction().reduce();
}
// 除法
public Fraction divide(Fraction other) {
int newNumerator = numerator * other.denominator;
int newDenominator = denominator * other.numerator;
return new Fraction(newNumerator, newDenominator).reduce().toImproperFraction().reduce();
}
// 输出假分数
@Override
public String toString() {
int wholeNumber = numerator / denominator;
int newNumerator = numerator % denominator;
return wholeNumber + " " + Math.abs(newNumerator) + "/" + denominator;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一个假分数的分子和分母:");
int numerator1 = scanner.nextInt();
int denominator1 = scanner.nextInt();
Fraction fraction1 = new Fraction(numerator1, denominator1);
System.out.print("请输入第二个假分数的分子和分母:");
int numerator2 = scanner.nextInt();
int denominator2 = scanner.nextInt();
Fraction fraction2 = new Fraction(numerator2, denominator2);
System.out.println("假分数加法结果为:" + fraction1.add(fraction2));
System.out.println("假分数减法结果为:" + fraction1.subtract(fraction2));
System.out.println("假分数乘法结果为:" + fraction1.multiply(fraction2));
System.out.println("假分数除法结果为:" + fraction1.divide(fraction2));
}
}
```
代码中使用了 `Fraction` 类来表示假分数,并提供了加减乘除运算的方法。在运算过程中,需要进行约分和转化为假分数的操作,最终输出的结果也是假分数的形式。在 `main` 方法中,从控制台输入两个假分数,然后输出它们的加减乘除结果。
阅读全文