gpt4 book ai didi

c++ - 猜猜我的号码 c++ while loop inside a loop

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:25 26 4
gpt4 key购买 nike

在学习 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) .

我可以在 do 中创建另一个 while 循环并确保 (tries < 6) .

这里最好的方法是什么?

最佳答案

您可以在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));
}

关于c++ - 猜猜我的号码 c++ while loop inside a loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55096936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com