为什么这个幂函数在负指数情况下返回零



该函数对所有负指数情况返回零:例如:print power(2, -3)返回 0

def power(int1, int2):
   if int2 == 0:
       return 1
   result = int1
   for num in range(1, int2):
       result*=int1
   if int2 > 0:
       return result
   else:
       return (1/result)

正确用法:

def power(int1, int2):
    result = int1
    for num in range(1, abs(int2)): #Must be positive value!  use "abs()"
        result*=int1
    if int2 == 0:
        return 1
    elif int2 > 0:
        return result
    else:
        return (1/result)
print(power(2, -3)) #OUTPUT: 0.125

相关内容

最新更新