这个程序有点问题。顺便说一下,我是递归的新手。不管怎样,我运行这个,我觉得它应该工作,但它只是成为一个无限循环。错误消息是“比较中超过了最大递归深度”。我只是从用户那里取一个数字,上下限,让计算机递归地猜出来。任何帮助都将不胜感激
import random as rand
def recursionNum(compGuess, magicNum):
#if the number that the user inputs for the computer to
#guess is to low it multiplies the number by 2 and then subtracts 1
#if the number is to high its divided(//) by 2 and then adds 1
if compGuess == magicNum:
print('You guessed right') #basecase
elif compGuess > magicNum:
print('Guess is', compGuess, '...Lower')
return recursionNum(compGuess //2+1, magicNum)
else:
print('Guess is', compGuess,'....Higher')
return recursionNum(compGuess *2-1, magicNum)
userNum =0
lowerLim = 0
upperLim = 0
while userNum not in range(lowerLim, upperLim):
lowerLim = int(input('What your lower limit: '))
upperLim = int(input('What is yor upper limit: '))
userNum = int(input('pick a number within your set limits:'))
compGuess = rand.randint in range(lowerLim, upperLim)
recursionNum(compGuess, userNum)
首先,您永远不会打印任何东西,因为print语句在return之后。Return将控制返回到调用作用域,因此将忽略Return语句后面的行。其次,没有理由为此使用递归。简单的for循环更适合这种情况。如果您正在寻找一个应用程序来练习递归,我可以推荐一个斐波那契数生成器吗?这是一个相当流行的例子
相关问题 更多 >
编程相关推荐