如何生成随机数?生成随机数的代码!

第一步-导入头文件

导入原函数文件 #include <stdio.h>
导入rand函数的头文件#include <stdlib.h>
导入time函数的头文件#include <time.h>

第二步-插入srand((unsigned)time(NULL));为随机数播下时间的种子。a = rand(); 结束

它的意思为读取当前系统的时间,将其作为随机数生成的种子。
解释:

  • srand对应rand()随即播种一个随机数种子。
  • unsigned 意思是无符号型变量,即时间。
  • time(NULL)抓取系统当前的时间,并将值返回出来。

代码举例:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
    int a;
    srand((unsigned)time(NULL)); 
    a = rand(); //a即为产生的随机数
    printf("%d",a);

    return 0;
}

附加、生成一定范围内的随机数

在使用随机数时我们通常要限制产生的随机数的范围,可以使用求余的方法。

对一个数字n取余结果的范围是 0~n-1
那么:a = rand() % 9 + 1; 代表只产生a=1~9之间的随机数字,其他范围同理。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
    int a;
    srand((unsigned)time(NULL)); 
    a = rand() % 12 + 3; //a的范围是3~14
    printf("%d",a);

    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。