作为程序员,没有合适的工具,就得手搓一个,PC端,移动端均可适用。废话不多说,直接上代码。
HTML:
<div class="calculator"><input id="values" type="text" placeholder="请输入值列表 (例如:1,2,3)"> <input id="probabilities" type="text" placeholder="请输入概率列表 (例如:0.2,0.5,0.3)"><button class="button" onclick="calculateExpectedValue()">计算期望值</button><div id="result" class="result">结果:期望值 =</div></div>
JS:
function calculateExpectedValue() {
const values = document.getElementById('values').value.split(',').map(Number);
const probabilities = document.getElementById('probabilities').value.split(',').map(Number);
// 检查输入有效性
if (values.length !== probabilities.length || values.length === 0) {
document.getElementById('result').innerText = "请确保值列表和概率列表长度相等";
return;
}
const probSum = probabilities.reduce((sum, p) => sum + p, 0);
if (Math.abs(probSum - 1) > 0.01) {
document.getElementById('result').innerText = "概率之和必须为 1";
return;
}
// 计算期望值
let expectedValue = 0;
for (let i = 0; i < values.length; i++) {
expectedValue += values[i] * probabilities[i];
}
document.getElementById('result').innerText = `结果:期望值 = ${expectedValue.toFixed(2)}`;
}
CSS:
.calculator {
width: 100%;
background-color: #333;
color: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}
label {
display: block;
margin-bottom: 10px;
font-size: 16px;
}
input, select {
width: 100%!important;
padding: 10px!important;
margin-bottom: 20px;
color: #000000;
border-radius: 5px;
border: 1px solid #555;
font-size: 16px!important;
background-color: #ffffff!important;
}
button {
width: 100%;
padding: 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
display: block;
margin: 0px;
margin-bottom: 20px;
margin-left: 0px!important;
}
button:hover {
background-color: orange;
}
.result {
margin-top: 20px;
text-align: center;
}
option {
background-color: #ffffff;
}
p {
font-size: 18px;
margin-top: 5px!important;
}