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)
  • 相关阅读:
    ZooKeeper详解
    数据结构与算法2——数组
    jquery复习笔记
    关于水平居中
    回顾这些日子
    阻止事件冒泡
    css导航栏
    js正则
    js事件绑定
    操作iframe
  • 原文地址:https://www.cnblogs.com/caoke/p/10518211.html
Copyright © 2011-2022 走看看