【问题标题】:Using python how do I repeatedly divide a number by 2 until it is less than 1.0?使用python如何重复将一个数字除以2直到它小于1.0?
【发布时间】:2016-12-01 16:32:16
【问题描述】:

我不确定如何创建循环以将数字除以二?请帮忙。我知道您可以将一个数字除以 2 不知道如何创建循环以继续除以直到小于 1.0。

【问题讨论】:

  • 请展示您尝试过的方法以及导致问题的原因。

标签: python python-3.x


【解决方案1】:

这取决于你到底在追求什么,因为问题并不清楚。将一个数字除以零直到小于 1.0 的函数如下所示:

def dividingBy2(x):

    while x > 1.0:
        x = x/2

但这除了理解 while 循环之外没有其他用途,因为它没有提供任何信息。如果你想知道在一个数字小于 1.0 之前你可以除以多少次,那么你总是可以添加一个计数器:

def dividingBy2Counter(x):

    count = 0

    while x > 1.0:
        x = x/2
        count = count + 1

    return count

或者,如果您想看到每个数字随着 x 变得越来越小:

def dividingBy2Printer(x):

    while x > 1.0:
        x = x/2
        print(x)

【讨论】:

    【解决方案2】:
    b=[]  #initiate a list to store the result of each division
    
    #creating a recursive function replaces the while loop
    #this enables the non-technical user to call the function easily
    
    def recursive_func(a=0):  #recursive since it will call itself later
    
        if a>=1:  #specify the condition that will make the function run again
            a = a/2 #perform the desired calculation(s)
            recursive_func(a) #function calls itself
            b.append(a)    #records the result of each division in a list
    
    #this is how the user calls the function as an example
    recursive_func(1024)
    print (b)    
    

    【讨论】:

    • 你能解释一下你的答案吗?
    • 该函数在每次除法后调用自身,同时满足条件(在本例中为 a>=1)。由于问题没有指定需要什么,我想将每个除法的结果添加到列表( b )中。如果需要,我们可以添加一个计数器来查看达到一个的步数。
    猜你喜欢
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 2016-02-26
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    相关资源
    最近更新 更多