嵌套While循环

时间:2014-07-17 19:59:28

标签: python while-loop nested

你好,我是Python的初学者。我编写了以下代码将数字转换为一个旁数。我用T计算这个数字可以减少两倍的次数。剩余的R在内循环中再次使用,但是我必须将T设置为0,如果我这样做,我会进入无限循环....有人可以帮助我吗?

import math

T=0 # timer to count homany times the given number can be divided by 2

G= int(input("nummer "))

A=G # save G in A, we need G later
R=G # the remainder also initialized with G

while R>1:
    print(T)
    while A>1:   
        A=int(A/2)
        T=T+1

        print(T)
        print(A)

    R=int(G-math.pow(2,T))

    A=R #use the remainder agin in the inner loop
    T=0 #set T to O, here it goes wrong, ill get an infinite loop!!! why

1 个答案:

答案 0 :(得分:0)

你只需要一个循环。此外,您可以使用模运算符(%)。

它的一般要点是......你想继续将数字除以2,直到达到0.当你去的时候,你想要在你去的时候添加REMAINDER(由%运算符计算)。 / p>

我不用python编程。 (不确定缩进,附加到列表,int(输入(“nummer”)),我假设是你要转换的数字。)

listToStoreAnswerInReverse = []
theNumberToConvert = int(input("nummer "))

while(theNumberToConvert != 0)
    remainder = theNumberToConvert % 2
    listToStoreAnswerInReverse.append([remainder])
    theNumberToConvert = theNumberToConvert / 2

listToStoreAnswerInReverse现在应该有二进制答案。请记住,这个答案将是相反的。因此列表中的第一个索引将包含二进制的最后一个值。

这是解决此问题的几种方法之一。您可以按建议使用内置或使用2的降序功能并减去。但是如果没有更多的研究,我不知道该怎么做。

相关问题