diff --git a/index.html b/index.html new file mode 100644 index 0000000..de2bbf3 --- /dev/null +++ b/index.html @@ -0,0 +1,26 @@ + + + + + + 进制转换器 + + + +
+

进制转换器

+ + + + + + + + + + +

+
+ + + \ No newline at end of file diff --git a/script.js b/script.js new file mode 100644 index 0000000..81a171d --- /dev/null +++ b/script.js @@ -0,0 +1,28 @@ +function convertBase() { + const inputNumber = document.getElementById('inputNumber').value.trim(); + const fromBase = parseInt(document.getElementById('fromBase').value); + const toBase = parseInt(document.getElementById('toBase').value); + + // 验证输入数字是否符合fromBase的规则 + if (!isValidNumber(inputNumber, fromBase)) { + alert('输入的数字无效!请检查其进制格式。'); + return; + } + + // 将输入的数字从fromBase转换为十进制 + const decimalValue = parseInt(inputNumber, fromBase); + + // 将十进制数转换为toBase + const result = decimalValue.toString(toBase).toUpperCase(); + document.getElementById('result').textContent = `转换结果: ${result}`; +} + +function isValidNumber(num, base) { + const validChars = '0123456789ABCDEF'.slice(0, base); + for (let char of num.toUpperCase()) { + if (!validChars.includes(char)) { + return false; + } + } + return true; +} \ No newline at end of file