winner4265975
public class Arithmetic {
private int a;
private int b;
private int c;
private int d;
//两个有理数分别是a/b和c/d;
public Arithmetic(int a,int b,int c,int d){
super();
if(b==0||d==0)
throw new RuntimeException("分母不能为零");
this.a=a;
this.b=b;
this.c=c;
this.d=d;
}
public String add(){
int remainder=greatestCommonDivisor(Math.abs(a*d+c*b),Math.abs(b*d));
return showAsFraction((a*d+c*b)/remainder,b*d/remainder);
}
public String sub(){
int remainder=greatestCommonDivisor(Math.abs(a*d-c*b),Math.abs(b*d));
return showAsFraction((a*d-c*b)/remainder,b*d/remainder);
}
public String multiply(){
int remainder=greatestCommonDivisor(Math.abs(a*c),Math.abs(b*d));
return showAsFraction(a*c/remainder,b*d/remainder);
}
public String divide(){
int remainder=greatestCommonDivisor(Math.abs(a*d),Math.abs(b*c));
return showAsFraction(a*d/remainder,b*c/remainder);
}
//求最大公约数
public int greatestCommonDivisor(int numerator ,int denominator){
int bigger;
int smaller;
if(numerator>denominator){
bigger=numerator;
smaller=denominator;
}else{
bigger=denominator;
smaller=numerator;
}
int remainder=bigger%smaller;
while(remainder!=0){
bigger=smaller;
smaller=remainder;
remainder=bigger%smaller;
}
return smaller;
}
public String showAsFraction(int numerator ,int denominator){
if((numerator>0&&denominator>0)||(numerator<0&&denominator<0))
return Math.abs(numerator)+"/"+Math.abs(denominator);
else
return "-"+Math.abs(numerator)+"/"+Math.abs(denominator);
}
}纯手打望采纳!