我在c++里有一个猜谜游戏程序。我是在一个嵌套的并发循环中完成的。我怎样才能使它进入while循环而不是do while?
发布于 2014-04-01 23:45:26
我为你的游戏循环创建了一个函数,让一切变得更清晰。还请注意,srand()正在寻找一个未签名的int。
#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;
}发布于 2014-04-01 18:14:17
您需要将猜测数字的代码放入函数中(例如,guessTheNumber)。一开始就叫一次。当它脱离循环后,它将从函数返回。在函数调用之后,询问用户是否想再试一次。如果是,则再次调用该函数(例如guessTheNumber),直到用户拒绝为止。一旦他们说不,就退出你的节目。这将减少到一个do/while循环。
伪码:
int main()
{
guessTheNumber();
Do you want to guess again?
if choice is yes, call guessTheNumber();
else
return 0;
}发布于 2014-04-01 19:05:06
你一定是新加坡人..。不管怎样,你可以试试这个。
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
https://stackoverflow.com/questions/22793074
复制相似问题