js红包算法随机分配

先假设一个红包四个人分,红包就是关于钱,那么是不是要保留两位小数,保留两位小数的方法很多,我用的方法是toFixed(2);

代码如下:

function fenpei(qian){
//第一个人
var one = (0.01 + Math.random()*(qian-(0.01*3))).toFixed(2);//qian-(0.01*3),因为如果到一个人如果抢到的是9.99的话,剩余0.01是不是不够三个人分,所以要减去人数的最小钱数,让第一个人最多只能抢到9.97 console.log(one);
//第二个人
var two = (0.01+Math.random()*((qian-one)-0.01*2)).toFixed(2); console.log(two); //第三个人 var three = (0.01+Math.random()*((qian-one-two)-0.01*2)).toFixed(2); console.log(three); //第四个人,用总钱数减去前面的就等于剩下的,为什么要加Number,因为是字符串所以要将他转为数字,如果你不转最后输出的结果为NaN var four =(qian- (Number(one)+Number(two)+Number(three))).toFixed(2); // console.log(Number(one)+Number(two)+Number(three)); console.log(four); }; fenpei(10);

为什么要加0.01,随机数出来是不是有可能0.0001或者更多的,四舍五入的话它就是0.00,所以这种情况是不是不能让他出现,所以就加上0.01,让他永远不会有四舍五入等于0.00的可能性。

运行结果:测试了20次

用sort排序取出最小值

function fenpei(qian){

    // console.log(arr.sort());
        var one = (0.01 + Math.random()*(qian-(0.80*3))).toFixed(2);
        console.log(one);

        var two = (0.01+Math.random()*((qian-one)-0.01*2)).toFixed(2);
        console.log(two);

        var three = (0.01+Math.random()*((qian-one-two)-0.01*2)).toFixed(2);
        console.log(three);

        var four =(qian- (Number(one)+Number(two)+Number(three))).toFixed(2);
        console.log(four);

        var money=[one,two,three,four];
        money.sort(function(a,b){
            return a-b;
        })
        var min=money.sort();
        console.log(money.sort());
        console.log(min[0]);

};
fenpei(10);

运行结果:

原文地址:https://www.cnblogs.com/yek9520/p/6599601.html