分数运算的程序
请人帮忙改下下面的程序,谢谢啦
class Rational
{
private int a;
private int b;
public Rational(int a,int b)
{
this.a = a;
this.b = b;
}
public Rational(int c)
{
this.c = c;
}
public int geta()
{
return geta;
}
public void geta(int a)
{
this.a = geta;
}
public int getb()
{
return getb;
}
public void getb(int b)
{
this.b = getb;
}
public Fraction add(Fraction summand)
{
if (this.b % summand.getb() == 0)
{
summand.seta(summand.geta() * (this.b / summand.getb()));
summand.setb(this.b);
}
else if (summand.getb() % this.b == 0)
{
this.seta(summand.a * (summand.getb() / this.b));
this.setb(summand.b);
}
else
{
int tmp = this.b;
this.setb(this.b * summand.getb());
this.seta(this.a * summand.getb());
summand.setb(tmp * summand.getb());
summand.seta(tmp * summand.geta());
}
return new Fraction(this.a + summand.geta(), this.b);
public int 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;
}
}
}
class shishu
{
public static void main(String[] args)
{
Fraction a = new Fraction(1, 1);
Fraction b = new Fraction(1, 2);
System.out.println(a.add(b));
}
}
[解决办法]
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());
}
}