牡丹江市网站建设_网站建设公司_字体设计_seo优化
2026/1/18 13:03:35 网站建设 项目流程

随机平分一个整数.分成24个数.尽量平均但不严格平均

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>整数随机拆分展示</title><style>.result-box {display: inline-block;margin-right: 5px;}</style><script>function splitAndDisplay() {const totalInput = document.getElementById('totalInput').value;const resultsContainer = document.getElementById('resultsContainer');if (!isNaN(totalInput) && totalInput >= 24) {const total = parseInt(totalInput);let remaining = total;const parts = new Array(23).fill(0); // 初始化23个0,因为最后一个会直接赋值剩余的数// 随机分配前23个数,尽量平均但不严格平均for (let i = 0; i < 23; i++) {const randomPart = Math.floor(Math.random() * (remaining / 2)) + 1; // 动态调整随机范围以接近平均,但不严格parts[i] = randomPart;remaining -= randomPart;}// 确保最后一个数补足总和
                parts.push(remaining);// 清空之前的显示并重新填充结果resultsContainer.innerHTML = '';parts.forEach((part, index) => {const resultBox = document.createElement('div');resultBox.className = 'result-box';resultBox.textContent = part;resultsContainer.appendChild(resultBox);});} else {alert("请输入一个大于等于24的整数。");}}</script>
</head>
<body><h2>输入一个整数:</h2><input type="number" id="totalInput"><button onclick="splitAndDisplay()">拆分并显示</button><h2>结果显示:</h2><div id="resultsContainer"></div>
</body>
</html>

 

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询