现在的位置: 首页 > 综合 > 正文

C和C++应用随机数

2013年03月09日 ⁄ 综合 ⁄ 共 1241字 ⁄ 字号 评论关闭

以下程序可以产生10个随机数,随机数范围0~100,并存入a[10]数组
#include <stdlib.h>     // srand()和rand()在stdlib.h中
#include <stdio.h>
#include <time.h>     // time()用于获取当前时间,一般把当前时间用于作为随机数种子使用
int main()
{
int i,a[10];
srand((unsigned)time(NULL)); //设置随机数种子
for(i=0;i<10;i++)
{
a[i]=rand()%100;   //产生0~99范围的随机数
printf("%2d.%3d\n",i+1,a[i]);
}
return 0;
}

 

因为C++兼容C,所以在C++中同样可以使用srand()和rand()两个函数产生随机数。srand()函数在cstdlib中,可以选取当前时间作为srand()函数的种子,就是说srand((int)time(NULL)),time()函数在ctime中;也可以自己指定种子值,例如:

#include<iostream>

using namespace std;

int main()

{

 int seed,a;

 cin>>seed;//输入一个数

 srand(seed);

 a = rand();

 cout<<a<<endl;

}

 

最后说一下设置随机数种子的srand()函数,一般系统会根据用户输入的数据不同而播种不同的种子。当你输入相同的数,将产生相同的随机数。例如:

#include <stdlib.h>
#include <stdio.h>
int main()
{
 int i,a[10];
 for(i=0;i<10;i++)
 {
  srand(53);  //设置随机数种子
  a[i]=rand();
  printf("%2d,%3d\n",i+1,a[i]);
 }
 return 0;
}

程序运行结果为:

  1,211

  2,211

  3,211

  4,211

  5,211

  6,211

  7,211

  8,211

  9,211

10,211

但是如果把srand()语句放在for循环外面,即每次不是设置好随机数种子后就产生随机数,则后面的for循环产生10个不同的随机数:

srand(53);  //设置随机数种子
 for(i=0;i<10;i++)
 { 
  a[i]=rand();
  printf("%2d,%3d\n",i+1,a[i]);
 }

运行结果:

  1,211

  2,20329

  3,17767

  4,32608

  5,31239

  6,23306

  7,9485

  8,8212

  9,828

10,32444

这样做虽然在一次程序执行过程中10个随机数各不相同,但是,这样的程序,每次执行后产生的结果都是一样的,也就是每次产生的10个随机数分别相等。

所以,一般用当前系统时间作为随机数种子,即

srand((unsigned)time(NULL));

这样,可以保证每次程序执行产生的随机数和前次程序执行结果不同

抱歉!评论已关闭.