我不确定如何创建循环以将数字除以2?请帮忙。我知道你可以将数字除以2而不知道如何创建循环以保持分割直到它小于1.0。
答案 0 :(得分:1)
这取决于您之后究竟是什么,因为它不能从问题中清除。将数字除以零直到小于1.0的函数将如下所示:
def dividingBy2(x):
while x > 1.0:
x = x/2
但除了理解while循环之外,这没有任何意义,因为它没有给你任何信息。如果你想看看在数字小于1.0之前可以除以2的次数,那么你总是可以添加一个计数器:
def dividingBy2Counter(x):
count = 0
while x > 1.0:
x = x/2
count = count + 1
return count
或者如果你想看到每个数字变得越来越小:
def dividingBy2Printer(x):
while x > 1.0:
x = x/2
print(x)
答案 1 :(得分:0)
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)