[英]I am making a code to turn a Binary number into decimal number, This is what I have done, Can someone tell where I am wrong, (i am 1 month into Python
n = int(input("Enter the binary number : "))
n_into_str = str(n)
lenf = len(n_into_str)
def calculate(n):
ans = 0
for i in range(lenf):
z = n%10
power = 2**i
k = z*power
value = z
ans = ans + z
print(ans)
calculate(n)
You are almost good, but you need ans = ans + k
and ans = ans + z
, and also divide n
by 10, to remove the last digit你几乎很好,但你需要ans = ans + k
和ans = ans + z
,并将n
除以 10,以删除最后一个数字
Version that uses math operation to select digit对 select 数字使用数学运算的版本
def calculate(n: int):
ans = 0
for i in range(len(str(n))):
z = n % 10
n = n // 10
power = 2 ** i
k = z * power
ans = ans + k
print(ans)
n = int(input("Enter the binary number : "))
calculate(n)
Version that uses string indexing to select digit使用字符串索引到 select 数字的版本
def calculate(n: str):
ans = 0
for i, digit in enumerate(reversed(n)):
power = 2 ** i
k = int(digit) * power
ans = ans + k
print(ans)
n = input("Enter the binary number : ")
calculate(n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.