要求:
1.生成一个随机数作为答案。
2.要求用户输入猜测的数字。
3.断用户猜测的数字是否与答案相同,如果不同则给出相应的提示信息,如“猜大了”、“猜小了”等。
4.循环进行猜测和提示,直到用户猜中为止。
5.可以设置猜测次数上限,超过上限未猜中则游戏失败。
代码:
#include <iostream>
#include<cstdlib> //包含rand()函数
#include<ctime> //包含time()函数
using namespace std;
int main()
{
cout << "猜数字:" << endl;
int num,max,min,m,n=0; //猜测值,最大值,最小值,猜测次数上限,猜测次数
cout << endl << "请输入随机数的最小值:";
cin >> min;
cout << endl << "请输入随机数的最大值:";
cin >> max;
cout << endl << "请输入需要猜测的次数:";
cin >> m;
//生成随机数
srand(time(nullptr)); //设定种子
int random_number = rand() % (max - min + 1) + min; //生成随机数并限定范围为min-max;
while (true)
{
++n;
cout <<endl << "请输入猜测的数字:";
cin >> num;
if (num == random_number) {
cout << "猜对了!" << endl;
break;
}
else
{
cout << "猜错了!" << endl;
if (num < random_number) cout << endl << "它比" << num << "要大";
else cout<< endl << "它比" << num << "要小";
}
if (n == m) {
cout <<endl << "游戏失败!";
break;
}
}
cout <<endl << "随机数为:" << random_number << endl;
system("pause");
}