猜数游戏(C++)

129 阅读1分钟

经典永不过时

代码如下:

#include <iostream>
#include <ctime>
using namespace std;
//要想每次产生的是不同的数要加这个


int main() {
	//添加随机数种子 作用利用当前系统的时间生成随机数,防止每次随机数都一样
	srand(time(NULL));//impotant
	//or srand((unsigned int)time(NULL)); 
	int num = rand() % 100 + 1;
	int n, i = 1;
	cout << "请输入一个数字" << endl;
	cin >> n;
	while (n != num) {
		if (n > num)
			cout << "您猜的数大了" << endl;
		else
			cout << "您猜的数小了" << endl;
		i++;
		cin >> n;
	}
	cout << "恭喜您猜对了,您只用了" << i << "次就猜到了答案" << endl;
	return 0;
}