fraction类的创建java_设计一个表示分数的类Fraction。这个类用两个int类型的变量分别表示分子和分母。(Java语言)...
时间: 2024-02-17 15:03:28 浏览: 75
类的构造和对象的是使用java 分数
好的,我理解了你的问题。下面是一个简单的Java代码,用于创建表示分数的Fraction类:
```
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 void setNumerator(int numerator) {
this.numerator = numerator;
}
public void setDenominator(int denominator) {
this.denominator = denominator;
}
public double getDecimalValue() {
return (double)numerator / denominator;
}
public Fraction add(Fraction otherFraction) {
int lcm = getLCM(this.denominator, otherFraction.getDenominator());
int newNumerator1 = this.numerator * (lcm / this.denominator);
int newNumerator2 = otherFraction.getNumerator() * (lcm / otherFraction.getDenominator());
int sum = newNumerator1 + newNumerator2;
return new Fraction(sum, lcm);
}
public Fraction subtract(Fraction otherFraction) {
int lcm = getLCM(this.denominator, otherFraction.getDenominator());
int newNumerator1 = this.numerator * (lcm / this.denominator);
int newNumerator2 = otherFraction.getNumerator() * (lcm / otherFraction.getDenominator());
int diff = newNumerator1 - newNumerator2;
return new Fraction(diff, lcm);
}
public Fraction multiply(Fraction otherFraction) {
int newNumerator = this.numerator * otherFraction.getNumerator();
int newDenominator = this.denominator * otherFraction.getDenominator();
return new Fraction(newNumerator, newDenominator);
}
public Fraction divide(Fraction otherFraction) {
int newNumerator = this.numerator * otherFraction.getDenominator();
int newDenominator = this.denominator * otherFraction.getNumerator();
return new Fraction(newNumerator, newDenominator);
}
private int getLCM(int a, int b) {
int gcd = getGCD(a, b);
return (a * b) / gcd;
}
private int getGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}
```
这个类包含了以下方法:
- 构造函数:通过传入分子和分母创建分数对象。
- get/set方法:用于获取和设置分子和分母的值。
- getDecimalValue方法:返回分数的十进制值。
- add/subtract/multiply/divide方法:用于对当前分数对象和另一个分数对象进行加、减、乘、除操作,返回一个新的Fraction对象。
- getLCM方法:用于获取两个数的最小公倍数。
- getGCD方法:用于获取两个数的最大公约数。
你可以根据自己的需求,添加更多的方法。希望这个代码对你有帮助!
阅读全文