#include<iostream>
#include<ctime>/*用srand((unsigned int)time(NULL));要包含这个头文件,如果没有这两个,rand()函数会一直生成42这个伪随机数。*/using namespace std;int main()
{srand((unsigned int)time(NULL));//种子,获取当前时间int num = rand() % 100 + 1;int key = 0;cout << "输入一个0-100的数字" << endl;cin >> key;while (key != num){if (key > num){cout << "猜大了,重猜" << endl;cin >> key;}else{cout << "猜小了,重猜" << endl;cin >> key;}}cout << "猜对了" << endl;system("pause");return 0;
}
以下是运行结果,每次这个随机数会不一样。