在学习C ++时,我有一个简单的猜测,就是我的数字代码。如您所见,它会选择一个随机数,并让用户猜测并记录尝试次数。
int main(){
srand(static_cast<unsigned int>(time(0))); // seed number generator
int secretNumber = rand() % 100 + 1;
int tries = 0;
int guess;
cout << "\tWelcome to Guess my Number\n\n";
do{
cout << "Enter a guess: ";
cin >> guess;
++tries;
if (guess > secretNumber){
cout << "Too high\n";
} else if (guess < secretNumber){
cout << "Too low \n";
} else {
cout << "You got it :) in " << tries << " tries \n\n";
}
} while(guess != secretNumber);
}
虽然这可以正常工作,但我也希望用户仅进行5次尝试。我可以考虑添加另一个else if
语句以确保(tries < 6)
。
OR
我可以在do
内创建另一个while循环,并确保(tries < 6)
。
这里最好的方法是什么?
答案 0 :(得分:4)
您可以将条件添加到do-while-loop
int main(){
srand(static_cast<unsigned int>(time(0))); // seed number generator
int secretNumber = rand() % 100 + 1;
int tries = 0;
int guess;
cout << "\tWelcome to Guess my Number\n\n";
do{
cout << "Enter a guess: ";
cin >> guess;
++tries;
if (guess > secretNumber){
cout << "Too high\n";
} else if (guess < secretNumber){
cout << "Too low \n";
} else {
cout << "You got it :) in " << tries << " tries \n\n";
}
} while((guess != secretNumber) && (tries < 6));
}
答案 1 :(得分:2)
另一种选择是使用for循环并中断正确答案:
int main(){
srand(static_cast<unsigned int>(time(0))); // seed number generator
int secretNumber = rand() % 100 + 1;
cout << "\tWelcome to Guess my Number\n\n";
for ( int tries = 1; tries < 6; tries++ ) {
int guess;
cout << "Enter a guess: ";
cin >> guess;
if (guess > secretNumber){
cout << "Too high\n";
} else if (guess < secretNumber){
cout << "Too low \n";
} else {
cout << "You got it :) in " << tries << " tries \n\n";
break;
}
}
}
答案 2 :(得分:0)
我不确定是否有最好的方法。如您所说,有两种可能性要么在
时添加条件while(guess != secretNumber && tries < 6);
或者您可以选择
else if(tries > 5)
{
cout << "You are out of tries, better luck next time ;) \n"
break;
}
我希望在while上添加条件的那个。但这是我的个人看法。我遇到一个程序员,如果它想做else并尝试使循环条件保持相对简单。使用更复杂的if / boolean语句,您可以提取具有正确名称的函数。在您的情况下,可以这样
bool isEndGame(int guess, int secretNumber, int tries)
{
return (guess != secretNumber) && (tries < 6);
}
int main()
{
srand(static_cast<unsigned int>(time(0))); // seed number generator
int secretNumber = rand() % 100 + 1;
int tries = 0;
int guess;
cout << "\tWelcome to Guess my Number\n\n";
do{
cout << "Enter a guess: ";
cin >> guess;
++tries;
if (guess > secretNumber){
cout << "Too high\n";
} else if (guess < secretNumber){
cout << "Too low \n";
} else {
cout << "You got it :) in " << tries << " tries \n\n";
}
} while (isEndGame(guess, secretNumber, tries));
}
我认为最后一个是最好的选择。您无需考虑条件,其他程序员现在可以清楚地了解其含义。