试图找出 python 中的 pow 源代码 |我的函数出错了
Trying to figure out pow source code in python | My function gone wrong
我正在做我的课本的练习,上面写着:
"Write a code in python which calculates the power of a number without using the function pow()."
我的功能的第一部分工作正常。但是说到#elif b > 1
它只是 returns a * b 的数量,而不是 a ** b ...
如果你能帮助我,我会很高兴。我至少花了 1 个小时来修复它。
def mypow(a,b):
if b == 0:
return 1
if b == 1:
return a
elif b > 1:
x = 0
for i in range(b):
x += 1 * a
return x
# I know I got to add what happens if the b is negative, but I will do this after fixing the bug.
这可能是因为您将 a
添加到 x
b
次。你应该乘,而不是加。
您似乎是在加法而不是乘法。
for i in range(b):
x *= a
你不需要 0 和 1 的特殊情况; b == 0
就够了。
def mypow(a, b):
answer = 1 # a ** 0 == 1
# The loop is only entered if b > 0
for _ in range(b):
answer *= a
return answer
我正在做我的课本的练习,上面写着:
"Write a code in python which calculates the power of a number without using the function pow()."
我的功能的第一部分工作正常。但是说到#elif b > 1
它只是 returns a * b 的数量,而不是 a ** b ...
如果你能帮助我,我会很高兴。我至少花了 1 个小时来修复它。
def mypow(a,b):
if b == 0:
return 1
if b == 1:
return a
elif b > 1:
x = 0
for i in range(b):
x += 1 * a
return x
# I know I got to add what happens if the b is negative, but I will do this after fixing the bug.
这可能是因为您将 a
添加到 x
b
次。你应该乘,而不是加。
您似乎是在加法而不是乘法。
for i in range(b):
x *= a
你不需要 0 和 1 的特殊情况; b == 0
就够了。
def mypow(a, b):
answer = 1 # a ** 0 == 1
# The loop is only entered if b > 0
for _ in range(b):
answer *= a
return answer