随机生成区间在1-100的数字,让用户猜大小,并给出提示
#include <iostream>
#include <random>
using namespace std;
int main() {
cout << "##猜数字游戏##" << endl;
//在1到100之间生成一个随机数
random_device rd; // Obtain a random number from hardware
mt19937 eng(rd()); // Seed the generator
uniform_int_distribution<> distr(1, 100); // Define the range
int Rnum = distr(eng); // Generate the random
int count = 0; //记录用户输入的次数
while (true) {
//用户输入的次数
count++;
//用户输入的数字
int guess;
cout << "请输入你猜的数字(1-100):";
cin >> guess;
//给予提示
if (guess > Rnum) {
cout << "太大了!" << endl;
}
else if (guess < Rnum) {
cout << "太小了!" << endl;
}
else {
cout << "恭喜你,猜对了!" << endl;
break;
}
}
//游戏结束,输出用户输入的次数
cout << "游戏结束" << endl;
cout << "你一共猜了" << count << "次。" << endl;
return 0;
}