如何重构此控制流以避免使用 goto?
作为我的入门编程课程的家庭作业,我必须设计并实现一个生成随机数(1-100)的程序,然后给玩家 7 次猜测以正确猜出该数字。我想出了这个算法:
但是,我不知道如何翻译这个概念表示将算法转化为控制结构。 (我们使用的是 Pascal,因此可用的结构是 if 语句、前序循环和后序循环)。前序循环和后序循环都不适合内循环,因为循环条件位于循环的中间,并且有两个退出点!
有人可以指导我如何更清晰地构建这个结构吗?
As a homework assignment for my introductory programming course I have to design and implement a program that generates a random number(1-100), then gives the player 7 guesses to correctly guess the number. I've come up with this algorithm:
However, I can't work out how to translate this conceptual representation of the algorithm into control structures. (We're using Pascal, so the structures available are if statements, pre-order loops, and post-order loops). Neither pre-order nor post-order looping fits for the inner loop, as the loop condition is in the middle of the loop and there are two exit points!
Could anybody give me a pointer on how to structure this more clearly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我根本不了解 Pascal,但我确实知道它有一个 while 循环...所以我会以类似于以下的方式构造它...(用伪代码编写)
I don't know Pascal at all, but I do know that it has a while loop...so I would structure it in a manner similar to the following...(written in pseudo-code)
我会用c风格写出来
LINK FOR WHILE LOOP IN PASCAL: http:/ /www.hkbu.edu.hk/~bba_ism/ISM2110/pas024.htm
i will write it out in c style
LINK FOR WHILE LOOP IN PASCAL: http://www.hkbu.edu.hk/~bba_ism/ISM2110/pas024.htm
对我来说它看起来很坚固。我不认识Pascal,但是你不能“打破”内循环吗?内部循环正在读取用户的猜测,显示提示并递增计数。它还检查两件事:猜测是否正确,以及计数小于 7。如果其中任何一个为真,它都会显示一条适当的消息,然后跳出内部循环,落入外部循环,然后询问用户是否想再玩一次。
It looks solid to me. I don't know Pascal, but can't you "break" out of the inner loop? The inner loop is reading the user's guess, showing a hint, and incrementing the count. It also checks two things: the guess is correct, and the count is less than 7. If either are true, it shows an appropriate message and then breaks out of that inner loop, falling into the outer loop where it then asks if the user wants to play again.