为什么对于负指数情况,此幂函数返回零?

时间:2019-01-07 22:48:10

标签: python function exponential

对于所有负指数情况,该函数返回零: 例如: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)

1 个答案:

答案 0 :(得分:0)

正确用法:

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