有理数类

有理数类的实现,有理数用分数表示,即分子分母,做加减乘除运算,除法时注意分母不能为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");
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值