public class Exp1 {
public static void main(String[] args) {
Fraction f1 = new Fraction(3, 5);
Fraction f2 = new Fraction(3, 7);
Fraction f3 = f1.divide(f2);
System.out.print(f3.getString());
}
}
public class Fraction {
//a是分子,b是分母
int a;
int b;
public Fraction(int a, int b) {
int c = gcb(a, b);
this.a = a / c;
this.b = b / c;
if(this.a * this.b < 0) {
this.a = Math.abs(this.a) * -1;
this.b = Math.abs(this.b);
}
}
//把当前分数转换为double值
double toDouble() {
return (double)a / b;
}
//将自己的分数和r的分数相加,返回一个新的Fraction的对象
Fraction plus(Fraction r) {
int newB = b * r.b;
int newA = a * r.b + r.a * b;
Fraction f = new Fraction(newA, newB);
return f;
}
//当前分数减去一个分数r,返回新的Fraction对象作为结果
Fraction minus(Fraction r) {
int newB = b * r.b;
int newA = a * r.b - r.a * b;
Fraction f = new Fraction(newA, newB);
return f;
}
Fraction multiply(Fraction r) {
int newA = this.a * r.a;
int newB = this.b * r.b;
Fraction f = new Fraction(newA, newB);
return f;
}
Fraction divide(Fraction r) {
int newA = this.a * r.b;
int newB = this.b * r.a;
Fraction f = new Fraction(newA, newB);
return f;
}
//返回整数a和b的最大公约数
int gcb(int a, int b) {
//(a和b的最大公约数)=(b和(a%b)的最大公约数)
int m;
while(b != 0) {
m = a % b;
a = b;
b = m;
}
return a;
}
//把当前分数转换为字符串形式
String getString() {
if(b == 1) {
return a + "";
} else {
return a + "/" + b;
}
}
}