我正在实施猜测游戏,其中计算机使用以下代码生成随机数:
int main()
{
srand(time(NULL));
while (true){
int num = rand() % 10, guess, tries = 0;
while (true){
cout << "Enter number 1 to 10:";
cin >> guess;
if (tries > 2)
{
break;
}
if (guess > num)
{
cout << "Too High ! Try again"<<endl;
}
if (guess > 10)
{
cout << "Error ReEnter 1 to 10\n";
}
else if (guess < num)
{
cout << "Too Low! Try again"<<endl;
}
else
{
break;
}
tries++;
}
if (tries > 2)
{
cout <<"\nYou ran out of tries!\n";
cout << "\nThe answer is:" << num << endl;
}
else
{
cout << "\nCONGRATZ!! You guess correctly!\n";
}
return 0;
}
}
其中一个问题是:当用户尝试3次时,即使用户输入在第3次尝试时输出正确,程序也会显示“用尽了”。
1.如何通知用户他们的输入超过10并向用户显示错误消息以输入1到10的值?
2.如何纠正上述问题?
答案 0 :(得分:1)
而不是为你编写程序这里有一些伪代码。
get a random number rand()%10+1 1..10 call it R
loop
get user input N
if N == R then show OK and break loop
if N < R show too low
else show too high
increment tries
if tries == 3 then break loop
end loop
答案 1 :(得分:0)
你有太多的if else
条件会使你的代码变得不必要地复杂,特别是回答你的第二个问题,不需要的行为是由以下原因引起的:
if (tries > 2)
{
break;
}
无论猜测如何都退出循环,因为它仅依赖于尝试次数。关于你的第一个问题,我决定为你提供更简单的实现,包括对它的回答。
您可以用while
循环替换do-while
循环,在猜测随机数时终止,即:
int main(){
// initialize random seed
srand (time(NULL));
// generate a random number within [1,10]
int secretRandom = rand() % 10 + 1;
// initialize
int yourGuess = 11;
// input loop
string promptMessage = "Type a a number from 1 to 10."
do{
cout << promptMessage << '\n';
// read input
cin >> yourGuess >> endl;
// guessed number relatively to the randomly generated
if (secretRandom < yourGuess) cout << "The secret number is lower\n";
else if (secretRandom > yourGuess) cout << "The secret number is higher\n";
}while(yourGuess != secretRandom)
// if you guess the random number exit the loop and display success message
cout << "You guessed right!\n";
return 0;
}
要将猜测量减少到特定数量,您可以将do-while
循环和成功消息括在for
循环中,例如:
int numberOfGuesses = 3;
for (int i = 0; i <= numberOfGuesses; ++i){
//...
}
如果您想强制用户输入1到10之间的数字,您可以通过以下方式执行此操作:
int yourGuess = 11;
int lowerBound = 0;
int upperBound = 10;
do{
cin >> yourGuess;
// not type safe
}while(yourGuess < lowerBound || yourGuess > upperBound);