rand()和srand()

C++中rand() 函数的用法

1、rand()不需要参数,它会返回一个从0到最大随机数的任意整数,最大随机数的大小通常是固定的一个大整数。

2、如果你要产生0~99这100个整数中的一个随机整数,可以表达为:int num = rand() % 100; 

     这样,num的值就是一个0~99中的一个随机数了。

3、如果要产生1~100,则是这样:int num = rand() % 100 + 1;  

4、总结来说,可以表示为:int num = rand() % n +a;

     其中的a是起始值,n-1+a是终止值,n是整数的范围。

5、一般性:rand() % (b-a+1)+ a ;    就表示  a~b 之间的一个随机整数。

6、若要产生0~1之间的小数,则可以先取得0~10的整数,然后均除以10即可得到“随机到十分位”的10个随机小数

     若要得到“随机到百分位”的随机小数,则需要先得到0~100的10个整数,然后均除以100,其它情况依 此类推。

7、通常rand()产生的随机数在每次运行的时候都是与上一次相同的,这样是为了便于程序的调试。

     若要产生每次不同的随机数,则可以使用srand( seed )函数进行产生随机化种子,随着seed的不同,就能够产生不同的随机数。

8、还可以包含time.h头文件,然后使用srand(time(0))来使用当前时间使随机数发生器随机化,这样就可以保证每两次运行时可以得到不同的随机数序列,同时这要求程序的两次运行的间隔超过1秒。

9、举例如下:

rand(产生随机数)
表头文件: #include<stdlib.h>
定义函数 :int rand(void)

函数说明 :
因为rand() 的内部实现是用线性同余法做的,它不是真的随机数,只不过是因为其周期特别长,所以有一定的范围里可看成是随机的,
rand() 会返回一随机数值,范围在 0 至 RAND_MAX 间。
在调用此函数产生随机数前,必须先利用 srand()设置好随机数种子,如果未设随机数种子,rand()在调用时会自动设随机数种子为 1。
rand()产生的是假随机数字,每次执行时是相同的。若要不同,以不同的值来初始化它.初始化的函数就是 srand()

返回值:
返回 0 至 RAND_MAX 之间的随机整数值,RAND_MAX 的范围最少是在 32767 之间(int),即双字节(16位数)。
若用unsigned int 双字节是 65535,四字节是 4294967295 的整数范围。
0~RAND_MAX 每个数字被选中的机率是相同的。

 

rand():

/* rand example: guess the number */
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main ()
{
  int iSecret, iGuess;

  /* initialize random seed: */
  srand (time(NULL));

  /* generate secret number between 1 and 10: */
  iSecret = rand() % 10 + 1;

  do {
    printf ("Guess the number (1 to 10): ");
    scanf ("%d",&iGuess);
    if (iSecret<iGuess) puts ("The secret number is lower");
    else if (iSecret>iGuess) puts ("The secret number is higher");
  } while (iSecret!=iGuess);

  puts ("Congratulations!");
  return 0;
}

Possible output:

Guess the number (1 to 10): 5
The secret number is higher
Guess the number (1 to 10): 8
The secret number is lower
Guess the number (1 to 10): 7
Congratulations!

 

srand(): 

/* srand example */
#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main ()
{
  printf ("First number: %d\n", rand()%100);
  srand (time(NULL));
  printf ("Random number: %d\n", rand()%100);
  srand (1);
  printf ("Again the first number: %d\n", rand()%100);

  return 0;
}

First number: 83

Random number: 68

Again the first number: 83  

posted @ 2019-01-21 18:49  lightmare  阅读(875)  评论(0编辑  收藏  举报