4.1分支和循环
1.随机数生成1.1rand函数1intrand(void);rand函数会返回⼀个伪随机数就是说运行多次结果返回的随机数是相同的。rand函数的使⽤需要包含⼀个头文件是stdlib.h随机数的范围是在0~RAND_MAX之间rand函 数是对⼀个叫“种⼦”的基准值进⾏运算⽣成的随机数。rand函数⽣成随机数的默认种⼦是1。如果要⽣成不同的随机数就要让种⼦是变化的:1.2srand用来初始化随机数的⽣成器1voidsrand(unsigned intseed);程序中在调⽤ rand 函数之前先调⽤ srand 函数通过 srand 函数的参数seed来设置rand函数⽣成随 机数的时候的种⼦只要种⼦在变化每次⽣成的随机数序列也就变化起来了。那也就是说给srand的种⼦是如果是随机的rand就能⽣成随机数在⽣成随机数的时候⼜需要⼀个随机数这就⽭盾了。1.3time在C语⾔中有⼀个函数叫time就可以获得这个时间time函数原型如下1time_ttime(time_t* timer);time 函数会返回当前的⽇历时间其实返回的是1970年1⽉1⽇0时0分0秒到现在程序运⾏时间之间的差值单位是秒timer 如果是⾮NULL的指针的话函数也会将这个返回的差值放在timer指向的内存中带回去如果 timer 是NULL就只返回这个时间的差值。time函数返回的这个时间差也被叫做时间戳time函数的时候需要包含头⽂件time.h如果只是让time函数返回时间戳我们就可以这样写1time(NULL);//调⽤time函数返回时间戳这⾥没有接收返回值所以生成随机数的代码#include stdio.h #include stdlib.h #include time.h srand((unsigned int)time(NULL)); printf(%d\n, rand());srand函数是不需要频繁调⽤的⼀次运行的程序中调⽤⼀次就够了。1.4设置随机数的范围⽣成a~b的随机数1a rand()%(b-a1)2.猜数字游戏实现#include stdio.h #include stdlib.h #include time.h void game() { int r rand() % 100 1; int guess 0; int count 5; while (count) { printf(\n你还有%d次机会\n, count); printf(请猜数字:); scanf(%d, guess); if (guess r) { printf(猜小了\n); } else if (guess r) { printf(猜大了\n); } else { printf(恭喜你猜对了\n); break; } count--; } if (count 0) { printf(你失败了正确值是:%d\n, r); } } void menu() { printf(************************\n); printf(****** 1. play *******\n); printf(****** 0. exit *******\n); printf(************************\n); } int main() { int input 0; srand((unsigned int)time(NULL)); do { menu(); printf(请选择:); scanf(%d, input); switch (input) { case 1: game(); break; case 0: printf(游戏结束\n); break; default: printf(选择错误重新选择\n); break; } } while (input); return 0; }