//添加随机数种子,作用:利用当前系统时间生成随机数,防止每次随机数都一样。
这里应添加 头文件:#include<ctime>
int main()
{
srand((unsigned int )time(NULL));
}
最终程序如下:
#include<iostream>
using namespace std;
#include<ctime>
int main()
{
srand((unsigned int)time(NULL));
int num = rand() % 100 + 1;
int val = 0;
while (1)
{
cout << " 请玩家猜数字" << endl;
cin >> val;
if (val > num)
{
cout << "猜测过大" << endl;
}
else if (val < num)
{
cout << "猜测过小" << endl;
}
else
{
cout << "恭喜您猜对了" << endl;
break;
}
}
return 0;
}