<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>分红包</title>
<style>
div{
padding: 10px;
}
</style>
</head>
<body>
<div><label>红包金额:<input type="text" id="account"></label></div>
<div><label>红包数量:<input type="text" id="count"></label></div>
<div><button id="start">随机生成</button></div>
<ul id="result"></ul>
</body>
<script>
const accountEl = document.getElementById('account');
const countEl = document.getElementById('count');
const btn = document.getElementById('start');
const result = document.getElementById('result');
function generate(account,count) {
let ret = [account];
while(count > 1){
// 取最大的进行分割
let cake = Math.max(...ret),
idx = ret.indexOf(cake),
part = 1 + Math.floor((cake / 2) * Math.random()),
rest = cake - part;
ret.splice(idx, 1, part, rest);
count-- ;
}
return ret;
}
btn.onclick = function () {
let account = Math.round(parseFloat(accountEl.value) * 100);
let count = parseInt(countEl.value);
let output = [];
if(isNaN(account) || isNaN(count) || account <= 0 || count <= 0){
output.push('格式不对');
}else if(account < count){
output.push('钱不够分')
}else{
output.push(...generate(account,count));
output = output.map(m => (m / 100).toFixed(2));
}
result.innerHTML = `<li>
${output.join('</li><li>')}
</li>`
}
</script>
</html>