我需要帮助创建一个使用while循环的函数,以便找到2的幂的乘积。在
问题是:
Create a Python function called
productOfPowersOf2
which takes two arguments, both of which are non-negative integers. For purposes of this problem, let's call the first argumentexp1
and the second argumentexp2
. Your function should compute and return (not print) the product of all powers of 2 from 2exp1 to 2exp2. Here are some examples of how your function should behave:>>> productOfPowersOf2(0,0) 1 >>> productOfPowersOf2(1,1) 2 >>> productOfPowersOf2(1,2) 8 >>> productOfPowersOf2(1,3) 64
我写的是:
def productsOfPowersOf2(exp1,exp2):
total=0
num=0
while num<=exp2:
total=(2**exp1)*(2**(exp1+num))
num=num+1
return(total)
但这行不通。有人能帮忙吗??在
这很有效:
我想任务是这么说的?在
1)您没有使用累积积;您只将
total
重新分配给下一个值。在换句话说,当循环退出时,你只得到这个值,这可能总是大于你想要的值,如果我不得不猜测的话
^{pr2}$提示:你可以用数学。
x^y * x^z = x ^ (y + z)
。求二的幂之前求指数的和。在扰流板
相关问题 更多 >
编程相关推荐