【发布时间】:2017-01-24 11:31:31
【问题描述】:
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main(){
int gnumber, rnumber;
char choice;
int tries;
do {
cout << "Welcome to the Number Guessing Game!" << endl;
cout << endl; // breakline
cout << "How many tries: ";
cin >> tries;
cout << endl;
while (tries > 0){
srand(time(NULL));
rnumber = rand() % 99;
cout <<"Enter an integer greater than or equal to 0 and less than 100:";
cin >> gnumber;
system("cls");
if (tries != 1){
if (gnumber < 100 && gnumber >= 0){
if (gnumber == rnumber){
cout << "Congratulations! You've guessed the number." << endl;
tries--;
cout << "Remaining tries: " << tries << endl;
}
else if (gnumber > rnumber){
cout << "Your guess is higher than the number." << endl;
tries--;
cout << " Guess Again!" << endl;
cout << "Remaining tries: " << tries << endl;
}
else{
cout << "Your guess is lower than the number." << endl;
tries--;
cout << " Guess Again!" << endl;
cout << "Remaining tries: " << tries << endl;
}
}
else
cout << "Must greater or equal to 0 and lesser than 100!" << endl;
}
else
{
cout << "Game over!" <<" The number is: " << rnumber << endl;
cout << "Play Again? (Y/N)" << endl;
cin >> choice;
system("cls");
}
}
}while(choice == 'Y' || choice == 'y'); //
system("pause");
return 0;
}
即使我输入 'N' 或 'n' 选项,它也不会停止循环。 即使我输入“Y”或“y”,它也不会询问我想要多少次尝试。 相反,它只是直接询问我想输入什么整数。 请尝试复制并编译代码以进一步了解问题所在。请帮忙。
P.S.:这是我顺便做的一个猜谜程序……
【问题讨论】:
-
您是否尝试过使用调试器单步执行您的代码?
-
当显示的代码中没有任何内容时,如果显示的代码响应“Y”、“y”、“N”或“n”,这将是一个非常好的技巧去做。你的问题是你的计算机只做你告诉它做的事情,而不是你想让它做的事情。
-
实际上是 'Y' 或 'y' 而不是 "Y" 或 "y" 因为选择被声明为 char 所以 'Y' 或 'y' 等于字母 Y 或 y。跨度>
标签: c++ if-statement nested-loops do-while nested-if