猜数字游戏
#include <iostream>
//time时间头文件
#include<ctime>
using namespace std;
int main() {
//添加随机数种子,利用当前系统时间生成随机数,防止每次随机数都一样
srand((unsigned int)time(NULL));
//rand()%100 随机生成0~99之间的一个数
int num = rand() % 100 + 1;
int count = 0;
while (true) {
int a;
cin >> a;
count++;
if (a == num) {
cout << "恭喜你猜对了" << endl;
break;
}
else if (a > num) {
cout << "你猜大了,请继续游戏" << endl;
}
else if (a < num) {
cout << "你猜小了,请继续游戏" << endl;
}
if (count >= 4) {
cout << "游戏次数已达上限,本次游戏失败" << endl;
break;
}
}
return 0;
}
随机生成字符串
#include <iostream>
using namespace std;
#include<string>
//生成字符串
string RandomStr(int len) {
srand((unsigned int)time(NULL));
string str;
char c;
for (int i = 0; i < len; i++) {
//随机生成26位英文小写字母
c = 'a' + rand() % 26;
str += c;
}
return str;
}
int main() {
string str = RandomStr(3);
cout << str << endl;
return 0;
}