我正在执行二进制计数器程序。我需要它来打印一个十进制等效项和相应的二进制等效项。...
到目前为止,我已经设法做到了这一点,但是我需要将二进制数从0转换为用户输入值,我一直在研究它,但是我想不通:可以提供任何帮助: )
Please enter number: 12
Decimal: 1 = binary: 1100
Decimal: 2 = binary: 1100
Decimal: 3 = binary: 1100
Decimal: 4 = binary: 1100
Decimal: 5 = binary: 1100
Decimal: 6 = binary: 1100
Decimal: 7 = binary: 1100
Decimal: 8 = binary: 1100
Decimal: 9 = binary: 1100
Decimal: 10 = binary: 1100
Decimal: 11 = binary: 1100
Decimal: 12 = binary: 1100
通过此代码
dec = input('Please enter number')
new_list = []
index = 0
output = ''
counter = 0
dec = int(dec)
upper_range = int(dec)
#for x in range(0,upper_range):
while dec > 0:
output += str(dec % 2)
dec = (dec // 2)
output = output[::-1]
new_list.append(output)
while counter < upper_range:
print('Decimal:', counter + 1, end=' ',)
print(' = binary:' , *new_list)
counter = counter + 1
答案 0 :(得分:0)
您应该在循环内进行十进制到二进制的转换;否则,它只会转换上限值:
dec = input('Please enter number')
counter = 1
upper_range = int(dec)
while counter <= upper_range:
binary = ''
dec = counter
while dec > 0:
binary += str(dec % 2)
dec = (dec // 2)
binary = binary[::-1]
print('Decimal:', counter, end=' ',)
print(' = binary:' , binary)
counter = counter + 1
答案 1 :(得分:0)
我认为这可能会回答您的问题。您可以使用内置的 bin 功能,也可以使用下面的 convTobin 方法手动进行操作。
#This is with the help of built-in
n = int(input())
for i in range(n+1):
print('Decimal: ',i,' Binary: ',bin(i).split('b')[1]);
#This is doing it manually
n = int(input())
def convTobin(num):
if num == 0:
return '0'
s = ''
while num:
s = str(num&1) + s
num = num>>1
return s
for i in range(n+1):
print('Deciaml: ',i,'Binary: ',convTobin(i))
答案 2 :(得分:0)
n = int(input(“请输入数字:”))
对于范围(1,n + 1)中的i:
const mainObject = {
"name": "Central",
"children": [
{
"Cellophane `Tape": 10.528979999999999,
"Cellophane Tape": 79.7194,
"File Separator": 64.0017,
"Hard Cover File": 23.2734,
"Highlighter": 67.2899,
"Office Chair": 74.2509,
"Pencil": 74.2509,
"Tape Dispenser": 67.2899,
"File Cabinet": 21.058,
"Plastic Comb Binding": 74.2509,
"White Board Markers": 74.2509,
"Binder": 67.2899,
"Eraser": 64.0017
}
]
}
let obj = mainObject.children[0]
var arr = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push(key + '=' + obj[key]);
}
};
let newArray = []
arr.map(item => {
newArray.push({"name": item.substr(0, item.indexOf('=')),
"value": item.substr(item.indexOf('=')+1, item.length) })
})
let result = {
"name" : mainObject.name,
"children" : newArray
}
console.log(result)