数学知识的应用(使用了BigInteger,1/3+1/6=1/2)

由于0.1+0.2!=0.3;
使用大整数来保存分子和分母即可。

这里写图片描述

package sf_05;
import java.math.BigInteger;
public class Main {
    public static class Rati{
        private BigInteger zi=BigInteger.ZERO;//令分子为0
        private BigInteger mu=BigInteger.ONE;//令分母为1

        //求取两个大整数的最大公约数。
        public static BigInteger gcd(BigInteger a,BigInteger b){
            if(b.equals(b.ZERO)) return a;
            return gcd(b,a.mod(b));
        }


        /*
         * 只有分子时,此时分母默认为1
         * 
         * BigInteger.valueOf(long x)
         */
        public Rati(long x){
            this(BigInteger.valueOf(x),BigInteger.ONE);
        }


        public Rati(long x,long y){
            this(BigInteger.valueOf(x),BigInteger.valueOf(y));
        }

        public Rati(BigInteger x, BigInteger y) {
            zi = x;
            mu = y;
            BigInteger g=gcd(zi,mu);
            zi=zi.divide(g);
            mu=mu.divide(g);
        }
        public Rati add(Rati it){
            return new Rati(zi.multiply(it.mu).add(mu.multiply(it.zi)),mu.multiply(it.mu));
        }
        public Rati mul(Rati it){
            return new Rati(zi.multiply(it.zi),mu.multiply(it.mu));
        }
        public String toString(){
            String s=zi.toString();
            if(mu.equals(BigInteger.ONE)==false) 
                s+="/"+mu;
            return s;
        }

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        /*
         * 有理数  1/3+1/6=1/2;
         */
        Rati x=new Rati(1,3).add(new Rati(1,6));
        System.out.print(x);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值