在这一节课里,我们综合之前课程的知识点来实现了一个猜数字的小游戏。首先让机器随机生成一个1到100之间的整数,然后在输出端提示用户输入一个整数来猜猜这个随机数是多少,获得输入后要先检测输入的内容是否是整数,不是的话要重新输入。接到合格的整数输入后,如果输入的数字与生成的随机数一致,则可提示成功后退出程序,否则程序会提示随机数比输入的数是高了还是低了,然后让用户再次输入猜测的数字,直到猜中为止。用流程图来描述这一过程的话,如下图:
随机数的生成需要用到3个函数rand, srand和time,time(0)函数返回一个以秒为单位的系统时间,这个秒数是从1970年1月1日午夜0时开始计算的,用它作为srand的参数时,系统可能会警告隐式转换失去整数精度的问题,可以用强制类型转换来解决,即在time(0)前加上(int)或者(unsigned int)。srand是为了生成随机数的种子,不同的种子,才能“长出”不同的随机数,如果不在使用rand函数之前调用srand函数,每次产生的随机数将不会发生变化。
srand((int)time(0));
为了生成一个1到100之间的随机数,在调用rand函数后让得到的值用100来取余,使值在0到99之间,再做加1操作即可。
int randomInt = rand()%100+1;
由于这里我用的开发工具是Xcode,在加入了预处理编译指令#include <iostream>后就不用再包含这几个函数所属的头文件stdlib.h和time.h了,但在其他的编译环境,可能还需在程序前面加上如下两条指令:
#include <stdlib.h>
#include <time.h>
获得随机数之后,就可以通过do-while(true)这样的无限循环结构来不断地让用户输入猜想的数字并和生成的随机数进行比较了,只有当猜想的数字和生成的随机数相等时才使用break;语句跳出这个无限循环。
完整程序实现如下:
1#include <iostream>
2
3int main(int argc, const char * argv[]) {
4 using std::cout;
5 using std::endl;
6 using std::cin;
7
8 int x;
9 srand((int)time(0));
10
11 int randomInt = rand()%100+1;
12 cout<<"A random integer (1 to 100) has been created."<<endl;
13 do{
14 cout<<"Please guess the number:"<<endl;
15
16 if(cin>>x&&cin.get()=='\n'){
17 if(x==randomInt){
18 cout<<"That's right! The number is "<<x<<endl;
19 break;
20 }else{
21 if(x<randomInt){
22 cout<<"The random number is higher."<<endl;
23 }else{
24 cout<<"The random number is lower."<<endl;
25 }
26 }
27 }else{
28 cin.clear();
29 cin.ignore(INT_MAX, '\n');
30 cout<<"Please input an integer!"<<endl;
31 }
32 }while(true);
33 return 0;
34}
转载请注明:XAMPP中文组官网 » C++编程实践 猜数字小游戏