You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.6 KiB

<!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; }
input { margin-bottom: 10px; }
</style>
</head>
<body>
<h1>进制转换程序</h1>
<label for="fromBase">输入进制 (R1):</label>
<input type="number" id="fromBase" value="10" min="2" max="16"><br>
<label for="numberX">输入数字 X:</label>
<input type="text" id="numberX"><br>
<label for="toBase">转换进制 (R2):</label>
<input type="number" id="toBase" value="10" min="2" max="16"><br>
<button onclick="convertBase()">转换</button>
<h2>转换结果 Y:</h2>
<p id="result"></p>
<script>
function convertBase() {
// 获取输入值
const fromBase = parseInt(document.getElementById('fromBase').value);
const numberX = document.getElementById('numberX').value.trim();
const toBase = parseInt(document.getElementById('toBase').value);
// 验证输入
if (!isValidNumberInBase(numberX, fromBase)) {
document.getElementById('result').innerText = "输入的数字 X 在指定的进制 R1 中无效!";
return;
}
// 将 X 从 R1 进制转换为十进制
const decimalValue = parseInt(numberX, fromBase);
// 将十进制转换为 R2 进制
const resultY = decimalToBase(decimalValue, toBase);
// 输出结果
document.getElementById('result').innerText = resultY;
}
function isValidNumberInBase(number, base) {
const validCharacters = '0123456789ABCDEF'.substring(0, base);
for (let char of number.toUpperCase()) {
if (!validCharacters.includes(char)) {
return false;
}
}
return true;
}
function decimalToBase(decimal, base) {
if (decimal === 0) return '0';
let result = '';
while (decimal > 0) {
const remainder = decimal % base;
result = (remainder < 10 ? remainder : String.fromCharCode(remainder - 10 + 'A'.charCodeAt(0))) + result;
decimal = Math.floor(decimal / base);
}
return result;
}
</script>
</body>
</html>