zoukankan      html  css  js  c++  java
  • 分数类 分子,分母

    //欧几里得算法 求两个数a、b的最大公约数
    function gcd(a,b){
        return b===0?a:gcd(b,a%b)
    }
    //分数类 分子,分母
    class Fraction{
        constructor(num=0,den=1){
            if(den<0){
                num=-num;
                den=-den;
            }
            if(den===0){
                throw '分母不能为0'
            }
            let g=gcd(Math.abs(num),den)
            this.num=num/g;
            this.den=den/g;
        }
        //
        add(o){
            return new Fraction(this.num*o.den+this.den*o.num,this.den*o.den)
        }
        //
        sub(o){
            return new Fraction(this.num*o.den-this.den*o.num,this.den*o.den)
        }
        //
        multiply(o){
            return new Fraction(this.num*o.num,this.den*o.den);
        }
        //
        divide(o){
            return new Fraction(this.num*o.den,this.den*o.num);
        }
        //小于
        lessThan(o){
            return this.num*o.den<this.den*o.num;
        }
        //等于
        equal(o){
            return this.num*o.den===this.den*o.num;
        }
    }
    
    let a=new Fraction(3,2)
    let b=new Fraction(5,6)
    let c=a.add(b)
    console.log(c)
  • 相关阅读:
    Linux
    Python
    Linux
    Python
    爬虫
    WEB
    法正(13):密谋
    法正(12):张松
    法正(11):入川
    法正(10):袍哥
  • 原文地址:https://www.cnblogs.com/caoke/p/10518211.html
Copyright © 2011-2022 走看看