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);

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM