繁体   English   中英

StackOverflow上的第一个计时器-递归遇到问题。 尝试让计算机递归猜测用户的号码

[英]First timer on StackOverflow---Having trouble with recursion. Trying to have the computer recursively guess the user's number

我在使用该程序时遇到了一些麻烦。 顺便说一下,我是递归的新手。 无论如何,我正在运行它,我觉得它应该可以工作,但这只是一个无限循环。 错误消息是“比较中超过了最大递归深度”。 我只是从用户那里获取数字,上限和下限,并让计算机递归地猜测它。 任何帮助将不胜感激!

游戏中计算机使用递归猜测用户的号码

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语句后的行将被忽略。 其次,没有理由为此使用递归。 一个简单的for循环更适合于此。 如果您只是在寻找可以进行递归的应用程序,我是否建议您使用斐波那契数生成器? 这是该主题相当受欢迎的示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM