首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >c++:从嵌套的do-while循环到嵌套的while循环

c++:从嵌套的do-while循环到嵌套的while循环
EN

Stack Overflow用户
提问于 2014-04-01 17:43:14
回答 6查看 1.2K关注 0票数 0

我在c++里有一个猜谜游戏程序。我是在一个嵌套的并发循环中完成的。我怎样才能使它进入while循环而不是do while?

EN

回答 6

Stack Overflow用户

发布于 2014-04-01 23:45:26

我为你的游戏循环创建了一个函数,让一切变得更清晰。还请注意,srand()正在寻找一个未签名的int。

代码语言:javascript
复制
#include <iostream>
#include <string>
#include <ctime>
using namespace std;

void rungame()
{
    int num = rand() % 10 + 0;
    int guess = -1;

    cout << "Guess a number between 0 - 10 : "<<endl;
    while (guess != num)
    {
        cin >> guess;
        if (guess > num)
        {
            cout << "Your guess is high . Guess again !"<<endl;
        }
        if (guess < num)
        {
            cout << "Your guess is low . Guess again !"<<endl;
        }
    }
}

int main()
{
    srand( (unsigned int) time(NULL) );
    string choice = "Yes";
    while (choice == "Yes")
    {
     rungame();
     cout << "That is Correct, You win"<<endl;
        cout <<"\nWould you like to give the game another try ? (Yes or no)"<<endl;
        cin>>choice;
    }
    return 0;
}
票数 1
EN

Stack Overflow用户

发布于 2014-04-01 18:14:17

您需要将猜测数字的代码放入函数中(例如,guessTheNumber)。一开始就叫一次。当它脱离循环后,它将从函数返回。在函数调用之后,询问用户是否想再试一次。如果是,则再次调用该函数(例如guessTheNumber),直到用户拒绝为止。一旦他们说不,就退出你的节目。这将减少到一个do/while循环。

伪码:

代码语言:javascript
复制
int main()
{
   guessTheNumber();
   Do you want to guess again?
   if choice is yes, call guessTheNumber();
   else
   return 0;
}
票数 0
EN

Stack Overflow用户

发布于 2014-04-01 19:05:06

你一定是新加坡人..。不管怎样,你可以试试这个。

代码语言:javascript
复制
cout << "Guess a number between 0 - 10 : "<<endl;
cin >> guess;

while(true)
{
        if (guess > num)
            cout << "Your guess is high . Guess again !"<<endl;
        else if (guess < num)    
            cout << "Your guess is low . Guess again !"<<endl;            
        else
        {
            cout << "That is Correct, You win"<<endl;
            cout <<"\nWould you like to give the game another try ? (Yes or no)"<<endl;
            cin>>choice;
            if (choice.compare("no")==0  //If user enter any other inputs, game continues
                 break;
        }
        cin >> guess;
} 

有几种方法可以实现这一点。在您的示例中,由于您已经在检查条件是否为num==guess,所以可以在while循环中删除该签入。使用while循环唯一的目的是循环。

显式地将“猜测”设置为不可能是"num“(例如set猜测=-1)的数字,感觉就像是硬编码。-P

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22793074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档