问题来了:
number = 1101
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#
#The number above represents a binary number. It will always
#be up to eight digits, and all eight digits will always be
#either 1 or 0.
#
#The string gives the binary representation of a number. In
#binary, each digit of that string corresponds to a power of
#2. The far left digit represents 128, then 64, then 32, then
#16, then 8, then 4, then 2, and then finally 1 at the far right.
#
#So, to convert the number to a decimal number, you want to (for
#example) add 128 to the total if the first digit is 1, 64 if the
#second digit is 1, 32 if the third digit is 1, etc.
#
#For example, 00001101 is the number 13: there is a 0 in the 128s
#place, 64s place, 32s place, 16s place, and 2s place. There are
#1s in the 8s, 4s, and 1s place. 8 + 4 + 1 = 13.
#
#Note that although we use 'if' a lot to describe this problem,
#this can be done entirely boolean logic and numerical comparisons.
#
#Print the number that results from this conversion.
这是我的代码
##Add your code here!
number_str = str(number) # "1101"
first_num = int(number_str[-1]) * 1
#print("first num:", first_num)
second_num = int(number_str[-2]) * 2
#print("second num:", second_num)
third_num = int(number_str[-3]) * 4
#print("Third num:", third_num)
fourth_num = int(number_str[-4]) * 8
#print("fourth num:", fourth_num)
fifth_num = int(number_str[-5]) * 16
sixt_num = int(number_str[-6]) * 32
seventh_num = int(number_str[-7]) * 64
decimal = first_num + second_num + third_num + fourth_num + fifth_num + sixt_num + seventh_num
print(decimal)
我得到的错误是: 我们发现您的代码有一些问题。第一个如下所示,其余的可以在左上角下拉列表中的 full_results.txt 中找到: 我们使用 number = 1010111 测试了您的代码。我们希望您的代码打印以下内容: 87 然而,它打印了这样的内容: 7
我知道我对这个问题进行了硬编码以容纳 4 位数字。我希望它适用于任何给定的数字,而不会引发 IndexError: string index out of range.
感谢您的帮助。
我不喜欢为人们做作业,但在这种情况下,我认为这个例子不仅仅是一个解释。
您可以从左到右一次转换一个字符。在每一步中,您将结果左移一位,如果数字是“1”,则将其添加进去。
number = 1011
decimal = 0
for c in str(number):
decimal = decimal * 2 + (c=='1')
print(decimal)
如果这太聪明了,请将
(c=='1')
替换为 int(c)
。
这就是我一直想告诉你的。您拥有的代码实际上会进行正确的转换,但只有当您恰好有 7 位数字时它才有效。您所需要做的就是更改代码,以便在尝试之前检查位数:
number = 1010111
num = str(number)
result = int(num[-1]) * 1
if len(num) > 1:
result += int(num[-2]) * 2
if len(num) > 2:
result += int(num[-3]) * 4
if len(num) > 3:
result += int(num[-4]) * 8
if len(num) > 4:
result += int(num[-5]) * 16
if len(num) > 5:
result += int(num[-6]) * 32
if len(num) > 6:
result += int(num[-7]) * 64
if len(num) > 7:
result += int(num[-8]) * 128
print(result)