最近在学习C++,遇到了一个案例:猜数字游戏
案例要求:系统生成一个范围在1-100的随机整数,用户有5次猜数字的机会,当用户猜的数字大于或小于生成的值时进行提示,5次没猜对则失败,猜对则成功;
代码:
#include#include #include using namespace std; int main(){ int rand_num = rand()%(1 - 100); cout << "rand_num = " << rand_num << endl; int user_input; int gameTime = 0; int maxGameTime = 5; cout << "请输入一个1-100的数字:" << endl; cin >> user_input; while (gameTime < maxGameTime){ if (user_input == rand_num){ cout << "恭喜你猜对啦!" << endl; break; } else if (user_input < rand_num){ gameTime ++; cout << "数字偏小了哦,再想想?剩余次数:" << maxGameTime - gameTime << endl; cout << "请输入一个1-100的数字:" << endl; cin >> user_input; } else if (user_input > rand_num){ gameTime ++; cout << "数字偏大了哦,再想想?剩余次数:" << maxGameTime - gameTime << endl; cout << "请输入一个1-100的数字:" << endl; cin >> user_input; } } return 0; }
第一次运行是可以的,但是反复运行后,发现每次生成的随机数都一样的,查了一下资料:
rand()函数生成随机数需要通过srand()函数设置一个随机数种子。srand()和rand()配合使用产生伪随机数序列。rand函数在产生随机数前,需要系统提供的生成伪随机数序列的种子
rand()根据这个种子的值产生一系列随机数。如果系统提供的种子没有变化,每次调用rand函数生成的伪随机数序列都是一样的。
srand(unsignedseed)通过参数seed改变系统提供的种子值,从而可以使得每次调用rand函数生成的伪随机数序列不同,从而实现真正意义上的“随机”。
通常可以利用系统时间来改变系统的种子值,即srand(time(NULL)),可以为rand函数提供不同的种子值,进而产生不同的随机数序列。
原来在C++中,需要生成随机种子去改变随机数序列,好,上代码:
#include#include #include using namespace std; int main(){ srand((unsigned)time(NULL)); int rand_num = rand()%(1 - 100); cout << "rand_num = " << rand_num << endl; int user_input; int gameTime = 0; int maxGameTime = 5; cout << "请输入一个1-100的数字:" << endl; cin >> user_input; while (gameTime < maxGameTime){ if (user_input == rand_num){ cout << "恭喜你猜对啦!" << endl; break; } else if (user_input < rand_num){ gameTime ++; cout << "数字偏小了哦,再想想?剩余次数:" << maxGameTime - gameTime << endl; cout << "请输入一个1-100的数字:" << endl; cin >> user_input; } else if (user_input > rand_num){ gameTime ++; cout << "数字偏大了哦,再想想?剩余次数:" << maxGameTime - gameTime << endl; cout << "请输入一个1-100的数字:" << endl; cin >> user_input; } } return 0; }
搞定~
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)