正在努力完成一项要求我在没有此运算符的情况下编写 a**b 的练习。尝试自己写一些东西,但没有得到正确的结果。我得到的不是一个值,而是两个,两者都不正确。看起来计数器并没有真正增加。我可以寻求帮助吗?谢谢!
def powerof(base,exp):
result=1
counter=0
# until counter reaches exponent, go on
if counter<=exp:
# result multiplies itself by base, starting at 1
result=result*base
# increase counter
counter=counter+1
return result
return counter # here it says "unreachable code". Can I not return more variables at the same time?
else: # counter already reached exponent, stop
return
# I want to print 2**8. Suprisingly getting two (incorrect) values as a result
print(powerof(2,8))
尝试使用递归:
def powerof(base,exp):
if exp == 0:
return 1
if exp == 1:
return base
return base * powerof(base, exp-1)
# I want to print 2**8. Suprisingly getting two (incorrect) values as a result
print(powerof(2,8))
那么它的作用是,在减少指数的同时调用自身,因此调用将如下所示:
2*(2*(2*2))) ...执行时。
您也可以在 for 循环中执行此操作,但递归更紧凑。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)