网页上做ppt的网站好,智能营销云,公文写作网站,东莞企业营销型网站策划#x1f970;欢迎关注 轻松拿捏C语言系列#xff0c;来和 小哇 一起进步#xff01;✊ #x1f389;创作不易#xff0c;请多多支持#x1f389; #x1f308;感谢大家的阅读、点赞、收藏和关注#x1f495; #x1f339;如有问题#xff0c;欢迎指正 感谢 目录
代码… 欢迎关注 轻松拿捏C语言系列来和 小哇 一起进步✊ 创作不易请多多支持 感谢大家的阅读、点赞、收藏和关注 如有问题欢迎指正 感谢 目录
代码
rand()
srand()
time()
设置随机数范围
产生a~b的随机数 运用循环、选择语句和函数我们可以制作一个简单的猜数字小游戏
假定游戏规则是给出一个1~100间的随机数我们在限定次数中去猜数字
代码
#includestdio.h
#includetime.h
#includestdlib.h
void menu()
{printf(---------------------------------\n);printf(---------** 1.play game **-----\n);printf(---------** 0.exit game **-----\n);printf(---------------------------------\n);
}
int main()
{int input;srand((unsigned int)time(NULL));//程序中只需要调用一次就可以了do{menu();int r rand() % 100 1;scanf(%d, input);printf(%d, r);switch (input){case 1:printf(游戏开始----);int count 5;int guess 0;while (count){printf(你还有%d次机会\n, count);printf(请猜数字\n);scanf(%d, guess);if (guess r)printf(猜大了\n);else if (guess r)printf(猜小了\n);else{printf(恭喜你猜对了\n);break;}count--;}if (count 0)printf(全部猜错游戏失败\n);break;case 0:printf(退出游戏);break;default:printf(输入错误请选择1或0\n);}} while (input);return 0;
}
运行截图 这里讲一下有关随机数生成的代码
rand() int rand (void); 使用要包含头文件stdlib.h
rand() 函数会返回一个伪随机数伪随机数范围是0~RAND_MAX大部分编译器上为32767
#include stdio.h
#include stdlib.h
int main()
{printf(%d\n, rand());printf(%d\n, rand());printf(%d\n, rand());printf(%d\n, rand());printf(%d\n, rand());return 0;
}第一次运行 第二次运行 可以看到两次运行产生的随机数是一样的这并没有实现真正的随机。
这是因为rand()函数产生的随机数是根据一个叫种子的基准值来计算的而rand函数的种子默认为1。
所以要产生随机数我们还需要让种子也变化起来
这里就需要srand()函数了
srand()
使用要包含头文件stdlib.h void srand (unsigned int seed); 在调用rand函数前调用srand函数通过srand函数的参数seed可以设置rand函数的种子使种子变化起来。
srand函数通常不需要在程序中频繁调用。
在大多数情况下你只需要在程序开始时调用一次srand函数来设置随机数生成器的种子。
time()
使用要包含头文件stdlib.h time_t time (time_t* timer); time函数会返回程序运行时间到1970年1月1日0时0分0秒的时间差也叫时间戳
time函数的参数 timer 如果是非NULL的指针的话函数也会将这个返回的差值放在timer指向的内存 中带回去。
如果 timer 是NULL就只返回这个时间的差值。
所以我们可以搭配这三个函数使用来产生真正的随机数 srand((unsigned int)time(NULL)); rand(); 设置随机数范围
上面游戏中我们需要产生1~100的随机数
写的 int r rand()%100 1;
如果要产生0~99的随机数 rand()%100; 产生100~200的随机数 100rand()%101或写成100rand()%(200-1001) 产生a~b的随机数 a rand()%(b-a1) 本文内容结束啦希望各位大佬多多指教
感谢大家三连支持
敬请期待下篇文章吧~