关于C语言中随机函数的使用详解

来源:互联网 发布:lol支持mac系统吗 编辑:程序博客网 时间:2024/05/17 23:53
  • C语言中大家都知道的随机函数为random,但是random函数并不是ANSI C标准,所以random函数不能在gcc或者vc等编译器下编译通过。

  • c语言中,rand()函数可以产生随机数,但其产生的随机数是固定的。

#include <stdio.h>#include <stdlib.h>int main(){    int x;    for (x = 0; x < 5; x++)    {        printf("%d\n", rand());        }    return 0;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

程序运行

多次运行以上程序产生的结果并未发生变化。 
至于rand()函数产生随机数的范围为0~RAND_MAX,在Linux平台RAND_MAX定义在stdlib.h, 其值为2147483647。

  • 那么如何产生真正意义上的随机数呢,

    这就需要调用srand()函数, 
    通过srand((unsigned)time(NULL))来实现

#include <stdio.h>#include <stdlib.h>#include <time.h>int main(){    int x;    srand((unsigned)time(NULL));    for (x = 0; x < 5; x++)    {        printf("%d\n", rand());        }    return 0;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

程序运行

可见每一次运行产生的随机数都不相同。

  • 如何产生设定范围内的随机数

    由于rand产生的随机数从0到rand_ max,而rand_ max是一个很大的数,那么如何产生一个设定范围内,例如从X ~ Y的数呢? 
    从X到Y,有Y-X+1个数,因此要产生从X到Y的数,需要这样编写 
    number = rand() % (Y - X + 1) + X;

例如:产生1~100的随机数

#include <stdio.h>#include <stdlib.h>#include <time.h>int main(){    int x;    srand((unsigned)time(NULL));    for (x = 0; x < 5; x++)    {        printf("%d\n", rand() % (100 - 1 + 1) + 1);        }    return 0;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

程序运行

以上就是我对随机函数的理解,希望对有需要的人能有所帮助。

原创粉丝点击