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.

120 lines
3.8 KiB

1 month ago
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>进制转换程序</title>
<style>
1 month ago
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
padding: 30px;
margin: 0;
}
h1 {
text-align: center;
color: #333;
}
.container {
background: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
max-width: 400px;
margin: 0 auto;
}
label {
margin-top: 10px;
font-weight: bold;
display: block;
}
input {
width: calc(100% - 20px);
padding: 10px;
margin: 5px 0 15px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
button {
background-color: #28a745;
color: #fff;
border: none;
padding: 10px;
border-radius: 4px;
cursor: pointer;
width: 100%;
}
button:hover {
background-color: #218838;
}
h2 {
text-align: center;
color: #333;
}
#result {
text-align: center;
font-size: 18px;
font-weight: bold;
color: #007bff;
}
1 month ago
</style>
</head>
<body>
1 month ago
<div class="container">
<h1>进制转换程序</h1>
<label for="fromBase">输入进制 (R1):</label>
<input type="number" id="fromBase" value="10" min="2" max="16">
<label for="numberX">输入数字 X:</label>
<input type="text" id="numberX" placeholder="例如A3">
<label for="toBase">转换进制 (R2):</label>
<input type="number" id="toBase" value="10" min="2" max="16">
<button onclick="convertBase()">转换</button>
<h2>转换结果 Y:</h2>
<p id="result"></p>
</div>
1 month ago
<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;
}
const decimalValue = parseInt(numberX, fromBase);
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>