C语言生成随机数代码

 1 #include <stdio.h>
 3 #include <stdlib.h>
 5 #include <time.h>
 7 int main() {
 9     int a;
11     srand((unsigned)time(NULL));  //读取系统时间,产生一个种子数值
13     a = rand();
15     printf("%d\n", a);    //可扩展为验证码代码
17     return 0;
19 }

生成一定范围内的随机数

在实际开发中,我们往往需要一定范围内的随机数,过大或者过小都不符合要求,那么,如何产生一定范围的随机数呢?我们可以利用取模的方法:

int a = rand() % 10;    //产生0~9的随机数,注意10会被整除

如果要规定上下限:

int a = rand() % 51 + 13;    //产生13~63的随机数

分析:取模即取余,rand()%51+13我们可以看成两部分:rand()%51是产生 0~50 的随机数,后面+13保证 a 最小只能是 13,最大就是 50+13=63。

代码示例:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int a;
srand((unsigned)time(NULL));
a = rand() % 51 + 13;
printf("%d\n",a);
return 0;
}

 




 

posted @ 2019-08-23 16:26  狗狗王  阅读(16817)  评论(0编辑  收藏  举报