From aca88be3e668ef27922b159ec1deae02cbfe7926 Mon Sep 17 00:00:00 2001 From: weiguang Date: Wed, 16 Oct 2024 16:02:50 +0800 Subject: [PATCH] =?UTF-8?q?html=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- index.html | 26 ++++++++++++++++++++++++++ script.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 index.html create mode 100644 script.js 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