我正在尝试设计一个递归函数,它接受来自用户的两个参数并将它们放入参数x和y中。该函数应返回x乘以y的值。我的代码无法正确执行,因为我试图在return语句中传递x和y变量,但我无法弄清楚我做错了什么。
def main():
#get the user to input a two integers and defines them as x and y
x = int(input("Please enter a positive integer: "))
y = int(input("Please enter a second positive integer: "))
#make sure the integer selection falls within the parameters
if (y == 0):
return 0
return x+(x,y-1)
#call the main function
main()
我的追溯说:
返回x +(x,y-1)TypeError:+:' int'不支持的操作数类型 和'元组'
答案 0 :(得分:1)
`您可以尝试这些方法:
def main():
#get the user to input a two integers and defines them as x and y
x = int(input("Please enter a positive integer: "))
y = int(input("Please enter a second positive integer: "))
print recursive_mult(x, y)
def recursive_mult(x, y):
if y == 0:
return 0
return x + recursive_mult(x, y - 1)
您看到的错误是由于尝试向x
的元组添加int值(x, y - 1)
引起的,而您可能希望对某些函数进行递归调用这些值并将结果添加到x。
答案 1 :(得分:1)
def main():
#get the user to input a two integers and defines them as x and y
x = int(input("Please enter a positive integer: "))
y = int(input("Please enter a second positive integer: "))
print( mul(x, y) )
def mul(x, y):
if y==0: return 0
return x + mul(x, y-1)