有理数类:
public class Rational {
public int i;
public int j;
public Rational(){
i=1;
j=1;
};
public Rational(int I,int J)
{
i=I;
j=J;
}
public void setRational(int I,int J)
{
i=I;
j=J;
}
public double getI(){return i;}
public double getJ(){return j;}
public Rational sum(Rational b){
Rational su=new Rational();
su.setRational((int)(i*b.getJ()+j*b.getI()),(int)(b.getJ()*j));
return su;
}
public Rational subtraction(Rational b){
Rational sub=new Rational();
sub.setRational((int)(i*b.getJ()-j*b.getI()),(int)(j*b.getJ()));
return sub;
}
public Rational multiplication(Rational b){
Rational mul=new Rational();
mul.setRational((int)(i*b.getI()),(int)(j*b.getJ()));
return mul;
}
public Rational division(Rational b){
Rational div=new Rational();
div.setRational((int)(i*b.getJ()),(int)(j*getI()));
return div;
}
public String toString()
{
return i+"/"+j;
}
}
有理数类的测试:
import java.util.Scanner;
public class RationalTest {
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
System.out.println("please enter two number");
Rational a=new Rational(in.nextInt(),in.nextInt());
System.out.println("please enter two number");
Rational b=new Rational(in.nextInt(),in.nextInt());
System.out.println("Rational a:"+a);
System.out.println("Rational b:"+b);
System.out.println("a+b:"+ a.sum(b).toString());
System.out.println("a-b:"+a.subtraction(b).toString());
System.out.println("a*b:"+a.multiplication(b).toString());
System.out.println("a/b:"+a.division(b).toString());
}
}