Compare commits

...

1 Commits
main ... hxt

Author SHA1 Message Date
hxt1218 532a0f3887 jzzh
8 months ago

@ -0,0 +1,67 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>进制转换</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
max-width: 400px;
}
label, input, button {
display: block;
margin-bottom: 10px;
}
#result {
font-weight: bold;
}
</style>
</head>
<body>
<h2>任意进制转换器</h2>
<label for="fromBase">输入进制 (2-16):</label>
<input type="number" id="fromBase" min="2" max="16" required>
<label for="number">输入数字:</label>
<input type="text" id="number" placeholder="例如1010" required>
<label for="toBase">转换为进制 (2-16):</label>
<input type="number" id="toBase" min="2" max="16" required>
<button id="convertButton">转换</button>
<h3>结果:</h3>
<div id="result"></div>
<script>
document.getElementById('convertButton').addEventListener('click', () => {
const fromBase = parseInt(document.getElementById('fromBase').value);
const number = document.getElementById('number').value.trim();
const toBase = parseInt(document.getElementById('toBase').value);
// 验证输入的数字是否合法
if (!/^[0-9A-Fa-f]+$/.test(number) || !isValidForBase(number, fromBase)) {
document.getElementById('result').textContent = '输入的数字不符合指定的进制规则!';
return;
}
// 转换为十进制
const decimalValue = parseInt(number, fromBase);
const convertedValue = decimalValue.toString(toBase).toUpperCase();
// 显示结果
document.getElementById('result').textContent = convertedValue;
});
function isValidForBase(numStr, base) {
const validChars = '0123456789ABCDEF'.slice(0, base);
return [...numStr].every(char => validChars.includes(char.toUpperCase()));
}
</script>
</body>
</html>
Loading…
Cancel
Save