繁体   English   中英

while循环中的字符串连接不起作用

[英]String concatenation in while loop not working

我正在尝试创建一个将十进制转换为二进制的Python程序。

目前我有

working = int(input("Please select a non-negative decimal number to convert to binary.  "))
x = ()

while working !=0:
    remainder = working % 2
    working = working // 2

    if remainder == 0:
      x = remainder + 0
      print (working, x)

    else:
     x = remainder + 1
    print (working, x)

print ("I believe your binary number is " ,x)

如果我在那之后打印,则while靠自己工作,但是if / else不能。 我正在尝试创建一个字符串,该字符串将添加到每个连续的除法中。 当前,如果我的起始int为76,则输出为

38 0
38 0
19 0
19 0
9 2
4 2
2 0
2 0
1 0
1 0
0 2

我试图让我的输出改为

38 0
19 00
9 100
4 1100
2 01100
1 001100
0 1001100

这是我第一次尝试进行字符串连接,并且我尝试了上述代码的一些变体以达到相似的结果。

问题是您不使用字符串。 首先要为x创建一个空元组,然后再用整数覆盖它。

要执行您要尝试的操作,您需要将x视为字符串,并在其后附加字符串文字'0''1'

尝试以下方法:

working = int(input("Please select a non-negative decimal number to convert to binary.  "))
x = ''

while working !=0:
    remainder = working % 2
    working = working // 2

    if remainder == 0:
        x += '0'
        print (working, x)

    else:
        x += '1'
        print (working, x)

print ("I believe your binary number is " , x[::-1])

请注意, x最初是如何声明为空字符串''而不是空tuple () 这样就可以在以后使用+=运算符向其附加0或1时将其视为字符串串联而不是加法。

您提供的代码存在一些问题:

  1. x()的值开头,在任何情况下,不是在其上串联字符串,而是在循环内添加数字。
  2. 您尝试添加数字而不是添加数字,因此,如果可行,结果将相反。
  3. 您的第二个print不在条件内,因此输出重复。

您需要做的是使用空字符串初始化x ,然后在其前面加上字符串:

working = int(input("Please enter a non-negative decimal number to convert to binary: "))
x = ""

while working != 0:
    remainder = working % 2
    working = working // 2

    if remainder == 0:
        x = "0" + x
    else:
        x = "1" + x

    print (working, x)

print ("I believe your binary number is", x)

输出:

λ python convert-to-binary.py
Please enter a non-negative decimal number to convert to binary: 76
38 0
19 00
9 100
4 1100
2 01100
1 001100
0 1001100
I believe your binary number is 1001100

它应该是

working = int(input("Please select a non-negative decimal number to convert to binary.  "))
x = ""

while working !=0:
    remainder = working % 2
    working = working // 2

    if remainder == 0:
      x = x + str(remainder)
      print (working, x)

    else:
     x = x + str(remainder)
    print (working, x)

print ("I believe your binary number is " ,x[::-1])

将您的代码更改为以下内容:

if remainder == 0:
    x = str(remainder) + '0'
    print (working, x)

else:
    x = str(remainder) + '1'
    print (working, x)

在您的代码中,python解释为int,您必须将其强制转换为字符串。

另一种方法是使用内置函数bin(working),将数字直接转换为二进制值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM