【发布时间】:2020-11-15 10:09:46
【问题描述】:
main_program = True
def program():
print('Hello user, please enter a value to choose an option')
print('select 1 to find the sum of two number')
print('select 2 to find the product two number')
print('select 3 to raise a number to a power')
print('4 to find the reminder two number')
print('select q for exit')
choice = input('human enter a value: ')
global main_program
while main_program:
if(choice == '1'):
sum_of_numbers()
elif(choice == '2'):
product_of_numbers(*get_information())
elif(choice == '3'):
esponent_of_numbers(*get_information())
elif(choice == '4'):
modulo_of_numbers(*get_information())
elif(choice == 'q'):
print('program terminated')
main_program = False
else:
print('wrong value entered')
def get_information():
while True:
try:
x = float(input('human enter a value: '))
y = float(input('human enter second value: '))
return x, y
except ValueError:
print('my processors cannot understand the inputs')
def sum_of_numbers():
x, y = get_information()
sum = x + y
print(sum)
program()
def product_of_numbers(x, y):
if(x < y):
print(product_of_numbers(y, x))
program()
if(x == 0):
print(0)
program()
else:
print(x + product_of_numbers(x, y-1))
program()
def esponent_of_numbers(x, y):
if y == 0:
print(1)
program()
elif y % 2 == 0:
print(esponent_of_numbers(x, y / 2)**2)
program()
else:
print(x * esponent_of_numbers(x, y-1))
program()
def modulo_of_numbers(x, y):
if x < y:
print(x)
print(modulo_of_numbers(x - y, y))
program()
program()
我需要你的帮助。我花了几个小时试图找出这些函数中的问题。 我的老师希望我使用给定 2 个数字的递归操作。 问题是每次我启动程序并初始化函数时都会出现此错误。 “RecursionError:调用 Python 对象时超出最大递归深度” 我没有使用位数,我正在关注 StackOverflow 中其他答案中关于相同参数的代码。 所以我想我真的没有掌握这个问题的概念:
如果用户在主菜单输入“1”: 应提示用户输入两个数字,然后求和(加法) 这两个数字将被打印到屏幕上。 要计算此值,您应该创建一个具有以下签名的函数 其中 x 和 y 可以是整数或浮点类型,返回答案:sum(x,y)。 如果用户在主菜单输入“2”: 应提示用户输入两个正数 x 和 y,以及产品 两个数字中的一个将打印到屏幕上。两个数的乘积可以是 表示为重复的加法运算。例如,54 = 20;这可以是 以另一种方式计算为 (5+5+5+5) = 20。 要计算此值,您应该创建一个具有以下签名的函数 其中 x 是 int 或 float,y 是 int,返回答案:prod(x,y)。 如果用户在主菜单输入“3”: 应提示用户输入两个正数 x 和 y。这 然后应将值 xyxy 打印到屏幕上。将 x 提高到 y 次方,可以 表示为重复乘法。例如,53=12553=125;这可以是 或者表示为55*5=125。 要计算此值,您应该创建一个具有以下签名的函数 其中 x 是整数,y 是整数,返回答案:exp(x,y)。 如果用户在主菜单输入“4”: 应提示用户输入两个正数 x 和 y。然后该值应打印到屏幕上。 x 和 y 的模得到余数 在⌊xy⌋⌊xy⌋之后,并且可以表示为重复减法。例如,5 模 2 = 1;这也可以表示为 5-2-2=1。 要计算此值,您应该创建一个具有以下签名的函数
【问题讨论】:
-
您的问题是什么?
-
第一个函数有效。对于其他三个,当他们从 get_information 返回值“RecursionError:调用 Python 对象时超出最大递归深度”时,我真的不知道为什么会发生这种情况
-
您的所有函数都重复调用其他函数。看起来在大多数情况下,你的函数永远不会返回,这意味着它们会不断地消耗内存,直到你的程序崩溃。与其再次调用
program来返回它,不如让函数结束。 -
虽然这不会是直接的问题。
modulo_of_numbers无限调用自己。 -
您需要将
print放在递归调用之前,否则将永远无法到达。