#include <iostream>
using namespace std;
/*
rand()%100:生成0-99之间的随机数
*/
int main()
{
int num1 = rand() % 100 + 1;//生成1-100之间的随机数,生成伪随机数42
int num2;
cin >> num2;
while (num1 != num2)
{
if (num1 > num2)
{
cout << "猜小了" << endl;
cin >> num2;
}
else
{
cout << "猜大了" << endl;
cin >> num2;
}
}
cout << "恭喜您猜到了!" << endl;
system("pause");
return 0;
}
优化版(对随机数生成进行优化):
#include <iostream>
using namespace std;
#include<ctime>
/*
()%100:生成0-99之间的随机数
2.使用系统时间需要添加头文件:#include<ctime>
((unsigned int)time(NULL))详解:/jx232515/article/details/51510336
*/
int main()
{
srand((unsigned int)time(NULL));//添加随机数种子,利用当前系统时间生成随机数,防止每次随机数都一样
int num1 = rand() % 100 + 1;//生成1-100之间的随机数
//cout << "随机数为" << num1 << endl;
int num2;
cin >> num2;
while (num1 != num2)
{
if (num1 > num2)
{
cout << "猜小了" << endl;
cin >> num2;
}
else
{
cout << "猜大了" << endl;
cin >> num2;
}
}
cout << "恭喜您猜到了!" << endl;
system("pause");
return 0;
}