<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
十进制转二进制<input type="text"><button>converse10to2</button><span class="one"></span></br>
二进制转十进制<input type="text"><button>converse2to10</button><span class="two"></span>
<script>
function converse10to2(x) {
var str = '';
function fn(x) {
if (x == 0) {
return 0;
} else {
fn(Math.floor(x / 2)); //向下取整
}
str += (x % 2);
}
fn(x);
if (str == '') {
str = '0';
x = 0;
}
return (x + "的十进制数为:" + str);
}
var btn2 = document.querySelectorAll("button")[0]
var span1 = document.querySelector('.one');
btn2.addEventListener('click', function() {
var input1 = document.querySelectorAll("input")[0].value;
var str = converse10to2(input1);;
span1.innerHTML = str;
})
function converse2to10(x) {
var s = 0;
var arr = x.split('');
arr = arr.map((item, index, arr) => {
return parseInt(parseInt(item) * Math.pow(2, arr.length - index - 1));
})
for (var i = 0; i < arr.length; i++) {
s += arr[i];
}
if (s == 0) {
x = 0;
}
return (x + "的十进制数为:" + s)
}
var btn2 = document.querySelectorAll("button")[1]
var span2 = document.querySelector('.two');
btn2.addEventListener('click', function() {
var input2 = document.querySelectorAll("input")[1].value;
var str = converse2to10(input2);
span2.innerHTML = str;
})
document.addEventListener('keydown', function(event) {
var event = event || window.event;
if (event.keyCode == 13) {
var input1 = document.querySelectorAll("input")[0].value;
var str = converse10to2(input1);;
span1.innerHTML = str;
var input2 = document.querySelectorAll("input")[1].value;
var str = converse2to10(input2);
span2.innerHTML = str;
}
})
</script>
</body>
</html>
二进制转十进制和十进制转二进制(js)
最新推荐文章于 2024-07-25 15:45:12 发布