简单的猜谜游戏继续使用声明变量以外的任何其他字母 Y/N
Simple guessing game continuing with any other letter other than the declared variable Y/N
我是一名有抱负的开发人员,我正在学习我的第一门语言 C++。我正在使用我从互联网和 YouTube 上学到的东西创建一个简单的猜谜游戏。几乎计算机会随机生成一个介于 0 和 5 之间的数字,您必须输入正确的数字。
问题是,在程序询问您的姓名(未存储)之后,它会询问您是否想玩一个要求输入 y 或 n 的游戏。 y 继续,n 关闭程序。
Y 应该继续游戏,但如果我输入另一个字母,例如 g,它会继续游戏。我将如何修复代码以仅允许变量 "y/Y" 继续游戏?
下面是代码。
#include <iostream>
#include <Windows.h>
#include <cmath>
#include <ctime>
#include <string>
using namespace std;
int main()
{
int num, numrand;
char yn;
string name;
srand(time(NULL));
cout << "Welcome to the program and please enter your name:";
cin >> name;
while (true)
{
cout << "Hello " << name << " do you want to play a game? (y/n): ";
cin >> yn;
if (yn == 'n' || yn == 'N')
return 0;
if (yn == 'y' || yn == 'Y');
break;
//If any other letter is used then it will continue. how to fix?
}
while (true)
{
cout << "computer will imagine one number from 0 to 5 and you will be given the task to guess it: ";
cin >> num;
numrand = rand() % 6;
if (numrand == num)
cout << "You Win!" << endl;
else if (num == -1)
break;
else
cout << "You Lose! The computer imagined the number: "<< numrand << endl;
}
system("pause");
return 0;
}
在 if 语句之后和休息之前你有一个意外的分号。
我是一名有抱负的开发人员,我正在学习我的第一门语言 C++。我正在使用我从互联网和 YouTube 上学到的东西创建一个简单的猜谜游戏。几乎计算机会随机生成一个介于 0 和 5 之间的数字,您必须输入正确的数字。
问题是,在程序询问您的姓名(未存储)之后,它会询问您是否想玩一个要求输入 y 或 n 的游戏。 y 继续,n 关闭程序。
Y 应该继续游戏,但如果我输入另一个字母,例如 g,它会继续游戏。我将如何修复代码以仅允许变量 "y/Y" 继续游戏?
下面是代码。
#include <iostream>
#include <Windows.h>
#include <cmath>
#include <ctime>
#include <string>
using namespace std;
int main()
{
int num, numrand;
char yn;
string name;
srand(time(NULL));
cout << "Welcome to the program and please enter your name:";
cin >> name;
while (true)
{
cout << "Hello " << name << " do you want to play a game? (y/n): ";
cin >> yn;
if (yn == 'n' || yn == 'N')
return 0;
if (yn == 'y' || yn == 'Y');
break;
//If any other letter is used then it will continue. how to fix?
}
while (true)
{
cout << "computer will imagine one number from 0 to 5 and you will be given the task to guess it: ";
cin >> num;
numrand = rand() % 6;
if (numrand == num)
cout << "You Win!" << endl;
else if (num == -1)
break;
else
cout << "You Lose! The computer imagined the number: "<< numrand << endl;
}
system("pause");
return 0;
}
在 if 语句之后和休息之前你有一个意外的分号。