有理数类的实现,有理数用分数表示,即分子分母,做加减乘除运算,除法时注意分母不能为0
import java.util.*;
public class Rational { //有理数类
int a; //分子
int b; //分母
void setaandb(int fenzi,int fenmu)
{
int n,m;
n=fenzi;
m=fenmu;
if(n<0)
n=n*(-1);
if(m<0)
m=m*(-1);
if(n==0)
{
a=0;
b=1;
return;
}
int c=gcd(n,m);
a=fenzi/c;
b=fenmu/c;
if(a<0&&b<0)
{
a=a*(-1);
b=b*(-1);
}
}
int geta()
{
return a;
}
int getb()
{
return b;
}
int gcd(int x,int y)
{
if(x<y)
{
int temp=x;
x=y;
y=temp;
}
int r=x%y;
while(r!=0)
{
x=y;
y=r;
r=x%y;
}
return y;
}
Rational add(Rational r)
{
int a1=r.geta();
int b1=r.getb();
int newa=a*b1+b*a1;
int newb=b*b1;
Rational result=new Rational();
result.setaandb(newa,newb);
return result;
}
Rational sub(Rational r)
{
int a1=r.geta();
int b1=r.getb();
int newa=a*b1-b*a1;
int newb=b*b1;
Rational result=new Rational();
result.setaandb(newa,newb);
return result;
}
Rational multi(Rational r)
{
int a1=r.geta();
int b1=r.getb();
int newa=a*a1;
int newb=b*b1;
Rational result=new Rational();
result.setaandb(newa,newb);
return result;
}
Rational div(Rational r)
{
int a1=r.geta();
int b1=r.getb();
int newa=a*b1;
int newb=b*a1;
Rational result=new Rational();
result.setaandb(newa,newb);
return result;
}
public static void main(String[] args) {
Rational r1=new Rational();
Rational r2=new Rational();
r1.setaandb(1,2);
r2.setaandb(3,4);
Rational result=r1.add(r2);
System.out.printf("1/2+3/4=%d/%d\n",result.a,result.b);
result=r1.sub(r2);
System.out.printf("1/2-3/4=%d/%d\n",result.a,result.b);
result=r1.multi(r2);
System.out.printf("1/2*3/4=%d/%d\n",result.a,result.b);
try //处理异常
{
if(r2.geta()==0)
{
demo();
}
else
{
result=r1.div(r2);
System.out.printf("(1/2)/(3/4)=%d/%d\n",result.a,result.b);
}
}
catch(Exception e)
{
System.out.print(e);
}
}
static void demo() throws Exception
{
throw new Exception("除数不能为0\n");
}
}