为什么这个幂函数 return 对于负指数情况为零?
Why does this Power function return zero for negative exponential cases?
函数 returns 对于所有负指数情况都为零:
例如:print power(2, -3)
returns 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
函数 returns 对于所有负指数情况都为零:
例如:print power(2, -3)
returns 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