Subtracting long numbers in javascript

后端 未结 6 1835
执笔经年
执笔经年 2020-12-02 01:44

Why is q == 0 in the following script?



        
6条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 02:25

    function add(x, y) {
        //*********************************************************************//
        // This function adds or subtracts two extremely large decimal numbers //
        // Inputs x and y should be numbers, i.e. commas are removed already   //
        // Use this function to remove commas and convert to number:           //
        // x = parseFloat(strNumber.replaceAll(",","").trim());                //
        // Inputs x and y can be both positive, or both negative,              //
        // or a combination (i.e. one positive and one negative in any         //
        // position whether as x or as y) which means subtraction              //
        //*********************************************************************//
    
        var temp, borrow=false, bothNeg=false, oneNeg=false, neg=false;
        if (x < 0 && y < 0) { bothNeg = true; x = -x; y = -y; } 
        else if (x < 0 || y < 0) {
            oneNeg = true;
            if (Math.abs(x) == Math.abs(y)) { x = 0; y = 0; }
            else if (x < 0 && Math.abs(x) > Math.abs(y)) { neg = true; x = -x; y = -y; }
            else if (x < 0 && Math.abs(x) < Math.abs(y)) { temp = y; y = x; x = temp; }
            else if (y < 0 && Math.abs(x) < Math.abs(y)) { neg = true; temp = y; y = -x; x = -temp; }
        }
        x = parseInt(x*1000000000/10).toString();
        y = parseInt(y*1000000000/10).toString();
        var lenx=x.length, leny=y.length, len=(lenx>leny)?lenx:leny, sum="", div=0, x1, y1, rem;
        for (var i = 0; i < len; i++) {
            x1 = (i >= lenx) ? 0 : parseInt(x[lenx-i-1]);
            y1 = (i >= leny) ? 0 : parseInt(y[leny-i-1]);
            y1 = (isNaN(y1)) ? 0 : y1;
            if (oneNeg) y1 = -y1;
            if (borrow) x1 = x1 - 1;
            if (y < 0 && x1 > 0 && Math.abs(x1) >= Math.abs(y1)) { borrow=false; div=0; }
            if (y < 0 && y1 <= 0 && (x1 < 0 || Math.abs(x1) < Math.abs(y1))) { borrow=true; rem=(x1+y1+div+10)%10; div=10; }
            else { rem=(x1+y1+div)%10; div=Math.floor((x1+y1+div)/10); }
            sum = Math.abs(rem).toString() + sum;
        }
        if (div > 0) sum = div.toString() + sum;
        sum = parseFloat(sum*10/1000000000);
        if (bothNeg || neg) sum = -sum;
        return sum;
    }
    

提交回复
热议问题