51,410
社区成员
发帖
与我相关
我的任务
分享public class Rational {
private int a;
private int b;
private int c;
public Rational() {
}
public Rational(int a, int b) {
this.a = a;
this.b = b;
}
/**
* @return the a
*/
public int getA() {
return a;
}
/**
* @param a
* the a to set
*/
public void setA(int a) {
this.a = a;
}
/**
* @return the b
*/
public int getB() {
return b;
}
/**
* @param b
* the b to set
*/
public void setB(int b) {
this.b = b;
}
/**
* @return the c
*/
public int getC() {
return c;
}
/**
* 分数相加
* @param summand
* @return
* @throws Exception
*/
public Rational add(Rational summand) throws Exception {
if(this.b==0){
throw new Exception("加数的分母不能为0");
}
if(summand.b==0){
throw new Exception("被加数的分母不能为0");
}
Rational retRational = new Rational();
if (this.b % summand.getB() == 0) {
retRational.setA(this.a+summand.getA() * (this.b / summand.getB()));
retRational.setB(this.b);
} else if (summand.getB() % this.b == 0) {
retRational.setA(summand.a+summand.a * (summand.getB() / this.b));
retRational.setB(summand.b);
} else {
retRational.setB(this.b * summand.getB());
retRational.setA(this.a * summand.getB()+this.b* summand.getA());
}
return retRational;
}
public String display() {
if (this.a % this.b == 0) {
return "" + this.a / this.b;
} else if (this.b % this.a == 0) {
return 1 + "/" + this.b / this.a;
} else {
return this.a + "/" + this.b;
}
}
public static void main(String[] args) throws Exception {
Rational a = new Rational(1, 4);
Rational b = new Rational(1, 2);
System.out.println("第一种情况:"+a.add(b).display());
Rational a1 = new Rational(1, 2);
Rational b1 = new Rational(1, 0);
System.out.println("第二种情况:"+a1.add(b1).display());
Rational a2 = new Rational(1, 3);
Rational b2 = new Rational(1, 4);
System.out.println("第三种情况:"+a2.add(b2).display());
}
}