如何重构此控制流程以避免使用goto?

时间:2011-04-27 13:42:36

标签: goto flowchart control-flow

作为我的入门编程课程的家庭作业,我必须设计并实现一个生成随机数(1-100)的程序,然后让玩家猜测正确猜测数字。我想出了这个算法:

control flow

但是,我无法弄清楚如何将算法的概念表示转换为控制结构。 (我们使用Pascal,因此可用的结构是if语句,预订循环和后序循环)。预循环和后序循环都不适合内循环,因为循环条件位于循环的中间,并且有两个退出点!

有人能给我一个关于如何更清楚地构建这个问题的指针吗?

3 个答案:

答案 0 :(得分:2)

我根本不知道Pascal,但我知道它有一个while循环...所以我会以类似下面的方式构造它...(用伪代码编写)

boolean userWishesToPlay = true;
int userGuess = -1;
int ranValue;
int guessCount = 0;

    while (userWishesToPlay) {
        ranValue = generateRandomValue();
        while(userGuess != ranValue && guessCount < 7) {
            // Give hint if user has guessed more than once
            if (guessCount >= 1) {
               // give hint
            }
            userGuess = // get input from user
            guessCount += 1;
        }

        if (userGuess == ranValue) {
           // print congrats!
        } else {
           // print game over
        }

        userWishesToPlay = // get input from user on whether to play again or not
        userGuess = -1; // since random value will be between 1 and 100 this is safe
        guessCount = 0;
    }

答案 1 :(得分:1)

我会用c风格写出来

bool gameover;

int tries = 0;

while(!gameover)
{
    game over = (tries > 7);
    if(answer == correct)
        break;
    tries++

}

在PASCAL中循环时的链接:http://www.hkbu.edu.hk/~bba_ism/ISM2110/pas024.htm

答案 2 :(得分:0)

对我来说看起来很稳固。我不知道Pascal,但你不能“打破”内循环吗?内循环正在读取用户的猜测,显示提示,并递增计数。它还检查两件事:猜测是正确的,并且计数小于7.如果其中任何一个为真,它显示一个适当的消息,然后突破该内部循环,落入外部循环,然后询问用户是否想再玩一次。

相关问题