[英]Exponential function return problem -python
我正在解决这个问题-
modify powerOfTwo() to meet the conditions below
# - accept 1 integer parameter; an exponent
# - print to the screen 2 raised to the exponent argument, example:
# --- "2 to the power of 2 is 4"
# - also return the result (for the example, you would return 4)
我的代码如下:
def powerOfTwo(exp):
x = int(input("please enter a number for what power of 2: "))
e = (2**x)
print("2 to the power of",x, "is: ",e,)
return (2**x)
运行该程序时,我教授的代码检查我的代码的准确性,并且我认为它检查不正确。 程序返回以下内容,其中包括我自己输入的“ 5”:
please enter a number for what power of 2: 5
2 to the power of 5 is: 32
+3 function call w/ correct # of params is present
+2 return value is correct type: <class 'int'>
-- return value is incorrect
Expected: 64
Returned: 32
期望值64显然是不正确的。 我的代码或教授的代码在检查我的问题是否有问题? (包括在下面):
q2s = 0
e = random.randint(3,11)
try:
print("\nq2-1: Checking powerOfTwo(" + str(e) + ")")
p2 = powerOfTwo(e)
print("+3 function call w/ correct # of params is present")
score += 3
q2s += 3
if isinstance(p2, int):
print("+2 return value is correct type:",type(p2))
score += 2
q2s += 2
if p2 == (2 ** e):
print("+2 return value is correct:",p2)
score += 2
q2s += 2
else:
print("-- return value is incorrect")
print("Expected: ",2 ** e)
print("Returned: ",p2)
e = random.randint(12,22)
print("\nq2-2: Checking powerOfTwo(" + str(e) + ")")
p2 = powerOfTwo(e)
if p2 == (2**e):
print("+2 return value is correct:",p2)
score += 2
q2s += 2
else:
print("-- return value is incorrect")
print("Expected: ",2**e)
print("Returned: ",p2)
else:
print("-- return value is incorrect type:",type(p2))
except:
print("**Something is wrong with powerOfTwo()")
printErr()
您教授的程序会生成一个随机数字,该数字将输入到您的函数中。 因此,您不能使用“输入”来输入您自己的号码。 您必须使用值'exp'。
您教授的代码会生成一个随机数,并将其放入函数中。 为了检查功能是否正常运行,您只需要输入生成的随机数即可。
此外,您似乎还没有初始化所提供的分数:
q2s = 0
e = random.randint(3,11)
score=0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.