【发布时间】:2016-12-01 16:32:16
【问题描述】:
我不确定如何创建循环以将数字除以二?请帮忙。我知道您可以将一个数字除以 2 不知道如何创建循环以继续除以直到小于 1.0。
【问题讨论】:
-
请展示您尝试过的方法以及导致问题的原因。
标签: python python-3.x
我不确定如何创建循环以将数字除以二?请帮忙。我知道您可以将一个数字除以 2 不知道如何创建循环以继续除以直到小于 1.0。
【问题讨论】:
标签: python python-3.x
这取决于你到底在追求什么,因为问题并不清楚。将一个数字除以零直到小于 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)
【讨论】:
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)
【讨论】: