function resPackage(money,num){// 总金额 目前剩余总金额let sum = money, currentsum = moneylet res = [];// 最大值for(let i = 0;i<num-1;i++){let n = parseFloat((Math.random()*currentsum).toFixed(2)) //0-10的随机数if(n<0.1) n = '0.1';if(n>sum-1) n = sum-1; //最大为money-1res.push(n);currentsum = currentsum-n;}let testsum = 0;for(let i = 0;i<res.length;i++){testsum += parseFloat(res[i])}let lastmax = sum-testsumres.push(parseFloat(lastmax.toFixed(2)))console.log(res)}resPackage(30,5)
-
要记得这里toFixed是将数字取二位小数转为字符串,转为字符串后然后要用parseFloat又转为数字,进行res求和
-
对最后一个数要进行特殊处理