【问题标题】:Binary to Decimal converter works backwards二进制到十进制转换器向后工作
【发布时间】:2014-07-31 13:42:39
【问题描述】:

我创建了一个将 8 位二进制转换为十进制的基本程序,但是当我运行该程序时,它会向后运行,例如如果我输入二进制数'00000001',程序将返回128。这是我的代码:

binaryvalue=input("Please enter your 8 bit binary number.")

binaryvalue=str(binaryvalue)

if len(binaryvalue) <= 8:

    print("Your number is accurate.")
    value_index=0
    total=0
    print("Your number is valid.")
    for i in range(len(binaryvalue)):
        total = total + (int(binaryvalue[value_index])) * 1 * (2**(value_index))
        value_index = value_index+1
    print("Your decimal number is: "+str(total))

【问题讨论】:

  • 为什么不反转输入?
  • 它必须以另一种方式工作-我的课程指定了它。
  • 那么向后循环?
  • 我的意思是在用户输入它之后 反转字符串。如果这是课程作业,您不应该自己做还是与老师交谈?
  • 您的问题是什么?如果是“为什么它不起作用”,那是因为您正在从高位迭代到低位。反转循环方向。

标签: python binary decimal converter


【解决方案1】:

所以,正如 jonrsharpe 和 Moe 所提到的

反转输入:

binaryvalue = str(binaryvalue)[::-1]

或者,您可以将偏移量放在您的权力范围内:

total = total + (int(binaryvalue[value_index])) * 1 * (2**(len(binaryvalue)-value_index-1))

不过,两者本质上都在做同样的事情。

【讨论】:

    猜你喜欢
    • 2016-08-26
    • 1970-01-01
    • 2018-04-03
    • 2020-06-27
    • 2015-02-27
    • 2020-06-25
    • 2012-05-28
    • 2013-05-14
    • 2017-06-04
    相关资源
    最近更新 更多