【Java】有理数四则运算

//有理数类
public class Rational {
    //成员变量
    private long a;//分子   
    private long b;//分母   

    //无参构造器
    public Rational() {
    }

    //最大公约数greatest common divisor
    private static long gcd(long x,long y)
    {
        if(x<0)x=-x;
        if(y<0)y=-y;
        if(y==0)return x;
        if(x==0)return y;
        return gcd(y,x%y);
    }

    //有参构造器//不能让分子分母最后的表达式有公约数
    public Rational(long a,long b) {
        long k=gcd(a,b);//a和b的最大公约数  
        a=a/k;b=b/k;   
        this.a=a;
        this.b=b;
    }
    
    //相加
    //新的有理数对象r1
    //r1.a分子,r1.b分母
    //原来的有理数对象
    //this.a分子 ,this.b分母
    
    //  (this.a/this.b)+(r1.a/ra.b)=(this.a*r1.b+this.b*r1.a)/(this.b*r1.b)
    
    public Rational add (Rational r1) {
        return new Rational(this.a*r1.b+this.b*r1.a  ,  this.b*r1.b);
    }
    
    
    //multiplication(乘法)
    public Rational mul(Rational r1)
    {
        return new Rational(this.a*r1.a  ,  this.b*r1.b);
    }
    
    //subtraction (减法)
    public Rational sub(Rational r1)
    {
        return new Rational(this.a*r1.b-this.b*r1.a  ,  this.b*r1.b);
    }
    

    //inverse(反转)
    public Rational inverse()
    {
        return new Rational(this.b,this.a);//分子分母颠倒
    }
    
    //division(除法)
    public Rational div(Rational r1)
    {
        return mul(r1.inverse());
    }

    //重写toString方法
    public String toString() 
    {
        if(b==1)
        {
            return " "+a;
        }
        else return a+"/"+b;
    }

    public static void main(String[] args) 
    {
        // TODO Auto-generated method stub
        Rational R1=new Rational(1,2);
        Rational R2=new Rational(1,4);
        
        Rational R3=R1.add(R2);
        Rational R4=R1.div(R2);
        
        System.out.println(R1);
        System.out.println(R3);
        System.out.println(R4);
    }
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

E02R26_骄言

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值