c++学习案例:猜数字游戏
2022/8/29 14:23:28
本文主要是介绍c++学习案例:猜数字游戏,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
最近在学习C++,遇到了一个案例:猜数字游戏
案例要求:系统生成一个范围在1-100的随机整数,用户有5次猜数字的机会,当用户猜的数字大于或小于生成的值时进行提示,5次没猜对则失败,猜对则成功;
代码:
#include <stdio.h> #include <iostream> #include <ctime> 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 <stdio.h> #include <iostream> #include <ctime> 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; }
搞定~
这篇关于c++学习案例:猜数字游戏的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-04-26高性能表格工具VTable总体构成-icode9专业技术文章分享
- 2024-04-16软路由代理问题, tg 无法代理问题-icode9专业技术文章分享
- 2024-04-16程序猿用什么锅-icode9专业技术文章分享
- 2024-04-16自建 NAS 的方案-icode9专业技术文章分享
- 2024-04-14ansible 在远程主机上执行脚本,并传入参数-icode9专业技术文章分享
- 2024-04-14ansible 在远程主机上执行脚本,并传入参数, 加上remote_src: yes 配置-icode9专业技术文章分享
- 2024-04-14ansible 检测远程主机的8080端口,如果关闭,则echo 进程已关闭-icode9专业技术文章分享
- 2024-04-14result 成功怎么写-icode9专业技术文章分享
- 2024-04-14stopped 状态设置为变量,由外部传递进来-icode9专业技术文章分享
- 2024-04-14为什么ansible执行远程脚本需要放到后台-icode9专业技术文章分享