简体   繁体   English

我正在编写将二进制数转换为十进制数的代码,这就是我所做的,有人可以告诉我哪里错了,(我进入 Python 1 个月

[英]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 + kans = 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.

相关问题 有人可以告诉我这个 python 代码哪里错了吗? - Can someone please tell me where am I wrong in this python code? 有人可以告诉我我做错了什么吗? - Can someone tell me what am I doing wrong? python程序告诉没有长度功能的代码中的单词数量?错误是意外的.plzz告诉我哪里错了 - python program to tell the number of words in code without length function?the error is unexpected .plzz tell where i am wrong 有人可以告诉我我的代码有什么问题吗? 我在调试时遇到问题 - Can someone tell me what is wrong with my code? I am having problems debugging 有人可以告诉我我做错了什么新到 Python - Can someone please tell me what am I doing wrong New to Python 我不明白为什么这段代码不起作用! 有人可以告诉我我做错了吗? - I don't see why this code is not working! can someone please tell me what i am doing wrong? 我哪里错了? - Where am I wrong? 分类到二进制-我在做什么错? - Categorical to Binary - what am I doing wrong? 一些输入的 output 应该是“错误的数字”,但我没有得到那个输入。 我究竟做错了什么? - The output for some of the inputs should be ‘Wrong number’ but I am not getting that input. What am I doing wrong? 我在哪里用这个装饰器代码犯了错误? - Where I am making a mistake with this decorator code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM