用java定义类Fraction,在其中定义属性:numerator和denominator,分别表示分子和分母。 然定再定义两个分数的加、减、乘、除运算的方法。 在主类中输入2个分数,计算它们的四则运算结果。
时间: 2024-10-24 12:13:42 浏览: 31
设计一个表示分数的类Fraction。这个类用两个int类型的变量分别表示分子和分母。
5星 · 资源好评率100%
在Java中,我们可以创建一个名为`Fraction`的类来定义分数,并为其提供属性和操作方法。首先,我们需要定义类的基本结构:
```java
public class Fraction {
private int numerator; // 分子
private int denominator; // 分母
public Fraction(int numerator, int denominator) {
if (denominator != 0) {
this.numerator = numerator;
this.denominator = denominator;
} else {
throw new IllegalArgumentException("Denominator cannot be zero.");
}
}
// 加法
public Fraction add(Fraction other) {
int newNumerator = this.numerator * other.denominator + other.numerator * this.denominator;
int newDenominator = this.denominator * other.denominator;
return new Fraction(newNumerator, newDenominator);
}
// 减法
public Fraction subtract(Fraction other) {
int newNumerator = this.numerator * other.denominator - other.numerator * this.denominator;
return new Fraction(newNumerator, this.denominator);
}
// 乘法
public Fraction multiply(Fraction other) {
return new Fraction(this.numerator * other.numerator, this.denominator * other.denominator);
}
// 除法,需要检查除数是否为0
public Fraction divide(Fraction other) {
if (other.denominator != 0) {
return new Fraction(this.numerator * other.denominator, this.denominator * other.numerator);
} else {
throw new ArithmeticException("Cannot divide by zero.");
}
}
@Override
public String toString() {
return "(" + numerator + "/" + denominator + ")";
}
}
```
接下来,在主类中你可以这样使用这个`Fraction`类来进行四则运算:
```java
public class Main {
public static void main(String[] args) {
Fraction f1 = new Fraction(4, 5);
Fraction f2 = new Fraction(2, 7);
System.out.println("f1: " + f1); // 输出第一个分数
System.out.println("f2: " + f2); // 输出第二个分数
// 计算并打印结果
Fraction sum = f1.add(f2);
Fraction difference = f1.subtract(f2);
Fraction product = f1.multiply(f2);
Fraction quotient = f1.divide(f2); // 这里假设其他不是零
System.out.println("Addition: " + sum);
System.out.println("Subtraction: " + difference);
System.out.println("Multiplication: " + product);
System.out.println("Division: " + quotient);
}
}
```
阅读全文