![C++随机数的生成_第1页](http://file3.renrendoc.com/fileroot_temp3/2022-1/6/06014eb7-c4c9-4ba9-b7de-5075ab2ef2f8/06014eb7-c4c9-4ba9-b7de-5075ab2ef2f81.gif)
![C++随机数的生成_第2页](http://file3.renrendoc.com/fileroot_temp3/2022-1/6/06014eb7-c4c9-4ba9-b7de-5075ab2ef2f8/06014eb7-c4c9-4ba9-b7de-5075ab2ef2f82.gif)
![C++随机数的生成_第3页](http://file3.renrendoc.com/fileroot_temp3/2022-1/6/06014eb7-c4c9-4ba9-b7de-5075ab2ef2f8/06014eb7-c4c9-4ba9-b7de-5075ab2ef2f83.gif)
![C++随机数的生成_第4页](http://file3.renrendoc.com/fileroot_temp3/2022-1/6/06014eb7-c4c9-4ba9-b7de-5075ab2ef2f8/06014eb7-c4c9-4ba9-b7de-5075ab2ef2f84.gif)
![C++随机数的生成_第5页](http://file3.renrendoc.com/fileroot_temp3/2022-1/6/06014eb7-c4c9-4ba9-b7de-5075ab2ef2f8/06014eb7-c4c9-4ba9-b7de-5075ab2ef2f85.gif)
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、例子:(只要在用rand()之前写srand(unsigned)time(0);产生的数就是随机数,可以不再同一个函数里,如下例)#include <iostream>/#include <time.h >#include <ctime>using namespace std;using std:cin;using std:cout;using std:endl;void cca()int t=0,CW,k=1;for(int j=0;j<7;j+)for(int i=0;i<10;i+)CW=rand()%7+4;if(i=0)t=CW;CW=
2、pow(2,CW*1.0)-1;cout<<CW<<' 'cout<<endl;getchar();void ke()cca();void main()srand(unsigned)time(0);ke();/getchar();标准库<cstdlib>(被包含于<iostream>中)提供两个帮助生成伪随机数的函数:函数一:int rand(void);从srand (seed)中指定的seed开始,返回一个seed, RAND_MAX(0x7fff))间的随机整数。函数二:void srand(unsigned s
3、eed);参数seed是rand()的种子,用来初始化rand()的起始值。可以认为rand()在每次被调用的时候,它会查看:1) 如果用户在此之前调用过srand(seed),给seed指定了一个值,那么它会自动调用srand(seed)一次来初始化它的起始值。2) 如果用户在此之前没有调用过srand(seed),它会自动调用srand(1)一次。根据上面的第一点我们可以得出:1) 如果希望rand()在每次程序运行时产生的值都不一样,必须给srand(seed)中的seed一个变值,这个变值必须在每次程序运行时都不一样(比如到目前为止流逝的时间)。2) 否则,如果给seed指定的是一个定
4、值,那么每次程序运行时rand()产生的值都会一样,虽然这个值会是seed, RAND_MAX(0x7fff))之间的一个随机取得的值。3) 如果在调用rand()之前没有调用过srand(seed),效果将和调用了srand(1)再调用rand()一样(1也是一个定值)。举几个例子,假设我们要取得06之间的随机整数(不含6本身):例一,不指定seed:for(int i=0;i<10;i+) ran_num=rand() % 6;cout<<ran_num<<" "每次运行都将输出:5 5 4 4 5 4 0 0 4 2例二,指定seed为定
5、值1:srand(1);for(int i=0;i<10;i+) ran_num=rand() % 6;cout<<ran_num<<" "每次运行都将输出:5 5 4 4 5 4 0 0 4 2跟例子一的结果完全一样。例三,指定seed为定值6:srand(6);for(int i=0;i<10;i+) ran_num=rand() % 6;cout<<ran_num<<" "每次运行都将输出:4 1 5 1 4 3 4 4 2 2随机值也是在0,6)之间,随得的值跟srand(1)不同,但是
6、每次运行的结果都相同。例四,指定seed为当前系统流逝了的时间(单位为秒):time_t time(0):#include <ctime>/srand(unsigned)time(0);for(int i=0;i<10;i+) ran_num=rand() % 6;cout<<ran_num<<" "第一次运行时输出:0 1 5 4 5 0 2 3 4 2第二次:3 2 3 0 3 5 5 2 2 3总之,每次运行结果将不一样,因为每次启动程序的时刻都不同(间隔须大于1秒?见下)。关于time_t time(0):time_t被定义
7、为长整型,它返回从1970年1月1日零时零分零秒到目前为止所经过的时间,单位为秒。比如假设输出:cout<<time(0);值约为1169174701,约等于37(年)乘365(天)乘24(小时)乘3600(秒)(月日没算)。另外,关于ran_num = rand() % 6,将rand()的返回值与6求模是必须的,这样才能确保目的随机数落在0,6)之间,否则rand()的返回值本身可能是很巨大的。一个通用的公式是:要取得a,b)之间的随机整数,使用(rand() % (b-a))+ a (结果值将含a不含b)。在a为0的情况下,简写为rand() % b。最后,关于伪随机浮点数:
8、用rand() / double(RAND_MAX)可以取得01之间的浮点数(注意,不同于整型时候的公式,是除以,不是求模),举例:double ran_numf=0.0;srand(unsigned)time(0);for(int i=0;i<10;i+) ran_numf = rand() / (double)(RAND_MAX);cout<<ran_numf<<" "运行结果为:0.716636,0.457725,等10个01之间的浮点数,每次结果都不同。如果想取更大范围的随机浮点数,比如110,可以将rand() /(double)(R
9、AND_MAX) 改为 rand() /(double)(RAND_MAX/10)运行结果为:7.19362,6.45775,等10个110之间的浮点数,每次结果都不同。至于100,1000的情况,如此类推。l C+中常用rand()函数生成随机数,但严格意义上来讲生成的只是伪随机数(pseudo-random integral number)。生成随机数时需要我们指定一个种子,如果在程序内循环,那么下一次生成随机数时调用上一次的结果作为种子。但如果分两次执行程序,那么由于种子相同,生成的“随机数”也是相同的。在工程应用时,我们一般将系统当前时间(Unix时间)作为种子,这样生成的随机数更接近
10、于实际意义上的随机数。给一下例程如下:#include <iostream>#include <ctime>#include <cstdlib>using namespace std;int main() double random(double,double); srand(unsigned(time(0); for(int icnt = 0; icnt != 10; +icnt)
11、; cout << "No." << icnt+1 << ": " << int(random(0,10)<< endl; return 0;double random(double start, double end) return start+(end-start)*rand()/(RAND_MAX + 1.0);/* 运行结果* No.1: 3* No.2: 9* No.3: 0* No.4: 9* No.
12、5: 5* No.6: 6* No.7: 9* No.8: 2* No.9: 9* No.10: 6*/利用这种方法能不能得到完全意义上的随机数呢?似乎9有点多哦?却没有1,4,7?!我们来做一个概率实验,生成1000万个随机数,看0-9这10个数出现的频率是不是大致相同的。程序如下:#include <iostream>#include <ctime>#include <cstdlib>#include <iomanip>using namespace std;int main() double random
13、(double,double); int a10 = 0; const int Gen_max = 10000000; srand(unsigned(time(0); for(int icnt = 0; icnt != Gen_max; +icnt) switch(int(random(0,10)
14、0; case 0: a0+; break; case 1: a1+; break; case 2: a2+; break; case 3: a3+; break; case 4: a4+; break;
15、 case 5: a5+; break; case 6: a6+; break; case 7: a7+; break; case 8: a8+; break; case 9: a9+; break;
16、60; default: cerr << "Error!" << endl; exit(-1); for(int icnt = 0; icnt != 10; +icnt) cout << icnt << ": " << setw(6) &
17、lt;< setiosflags(ios:fixed) << setprecision(2) << double(aicnt)/Gen_max*100 << "%" << endl; return 0;double random(double start, double end) return start+(end-start)*rand()/(RAND_MAX + 1.0);/* 运行结果* 0: 10.01%
18、* 1: 9.99%* 2: 9.99%* 3: 9.99%* 4: 9.98%* 5: 10.01%* 6: 10.02%* 7: 10.01%* 8: 10.01%* 9: 9.99%*/可知用这种方法得到的随机数是满足统计规律的。用C语言产生随机数在C语言中,rand()函数可以用来产生随机数,但是这不是真真意义上的随机数,是一个伪随机数,是根据一个数,我们可以称它为种子,为基准以某个递推公式推算出来的一系数,当这系列数很大的时候,就符合正态公布,从而相当于产生了随机数
19、,但这不是真正的随机数,当计算机正常开机后,这个种子的值是定了的,除非你破坏了系统,为了改变这个种子的值,C提供了srand()函数,它的原形是void srand( int a)。可能大家都知道C语言中的随机函数random,可是random函数并不是ANSI C标准,所以说,random函数不能在gcc,vc等编译器下编译通过。rand()会返回一随机数值,范围在0至RAND_MAX 间。返回0至RAND_MAX之间的随机数值,RAND_MAX定义在stdlib.h,(其值至少为32767)我运算的结果是一个不定的数,要看你定义的变量类型,int整形的话就是32767。 在调用此函数产生随
20、机数前,必须先利用srand()设好随机数种子,如果未设随机数种子,rand()在调用时会自动设随机数种子为1。一般用for语句来设置种子的个数。具体见下面的例子。 一 如何产生不可预见的随机序列呢利用srand(unsigned int)(time(NULL)是一种方法,因为每一次运行程序的时间是不同的。 在C语言里所提供的随机数发生器的用法:现在的C编译器都提供了一个基于ANSI标准的伪随机数发生器函数,用来生成随机数。它们就是rand()和srand()函数。这二个函数的工作过程如下:1) 首先给srand
21、()提供一个种子,它是一个unsigned int类型,其取值范围从065535;2) 然后调用rand(),它会根据提供给srand()的种子值返回一个随机数(在0到32767之间)3) 根据需要多次调用rand(),从而不间断地得到新的随机数;4) 无论什么时候,都可以给srand()提供一个新的种子,从而进一步“随机化”rand()的输出结果。 下面是032767之间的随机数程序:#include <stdlib.h>#include <stdio.h>#include <time.h>
22、60; /使用当前时钟做种子void main( void )int i;srand( (unsigned)time( NULL ) ); /初始化随机数 for( i = 0; i < 10;i+ )
23、0; /打印出10个随机数 printf( " %dn", rand() ); 根据上面的程序可以很容易得到01之间的随机数:#include <stdlib.h>#include <stdio.h>#include <time.h> main
24、( )int i;srand( (unsigned)time( NULL ) ); for( i = 0; i < 10;i+ ) printf( "%5.2fn", rand()/32767.0); 而产生1100之间的随机数可以这样写:#include <stdlib.h>#include
25、<stdio.h>#include <time.h> main( )int i;srand( (unsigned)time( NULL ) ); for( i = 0; i < 10;i+ ) printf( "%dn", rand()%100+1);come from 二,三个通用的随机数发生器,推荐用第三个函数名: rand
26、功 能: 随机数发生器 用 法: void rand(void); 程序例: #include <stdlib.h> #include <stdio.h> int main(void) int i; printf("Ten random numbers from 0 to 99nn"); for(i=0; i<10; i+) printf("%dn", rand(
27、) % 100); return 0; 函数名: random 功 能: 随机数发生器 用 法: int random(int num); 程序例: #include <stdlib.h> #include <stdio.h> #include <time.h> /* prints a random number in the range 0 to 99 */ int main(void) randomize(); printf("R
28、andom number in the 0-99 range: %dn", random (100); return 0; 函数名: randomize 这个比较好!功 能: 初始化随机数发生器 用 法: void randomize(void); 程序例: #include <stdlib.h> #include <stdio.h> #include <time.h> int main(void)
29、 int i; randomize(); printf("Ten random numbers from 0 to 99nn"); for(i=0; i<10; i+) printf("%dn", rand() % 100); return 0; 在计算机常用算法中有介绍随机数的生成算法 三 如何产生设定范围内的随机数 由于
30、rand产生的随机数从0到rand_max,而rand_max是一个很大的数,那么如何产生从XY的数呢? 从X到Y,有YX1个数,所以要产生从X到Y的数,只需要这样写: k=rand()%(Y-X+1)+X; 这样,就可以产生你想要的任何范围内的随机数了。四,产生不重复的随机数1) #include <stdlib.h> #include <stdio.h> #include<stdio.h> #include <time.h>
31、; swap(int *pm,int *pn) /*必须用指针进行交换*/ int temp; temp=*pm; *pm=*pn; *pn=temp;int main(void)int i,a513;/*int *pa,*pb;*/srand( (unsigned)time( NULL ) ); /*定义这个可以产生不同的随机数*/for(i=1; i<=512;
32、; i+)ai=i;printf("%4d",ai);for(i=512; i>=1; i-) /* pa=&ai; pb=&arand()%i+1;*/ swap(&ai, &arand()%i+1); /*加一是从一到i的随机,就不会包含0*/ /*不用再定义指针,这样结论是一样的*/ printf("n") ; for(i=1
33、; i<=64; i+) printf("%4d",ai );getch(); /*wintc的输出*/2) #include <stdlib.h> #include <stdio.h> #include<stdio.h>int main(void) int a100=0; int i,m; for(i=1; i<=99;
34、60; +i) printf("%4d",ai );srand( (unsigned)time( NULL ) );for(i=1; i<=99; i+) while(am=rand()%100+1); am = i; for(i=1; i<=
35、99; +i) printf("%4d",ai );getch();/ Snake.cpp : 定义控制台应用程序的入口点。/This program is used to collect the most mark and output the routine./by nwpu043814/date:20100509#include "stdafx.h"#include <iostream>#include <fstream>#include <vec
36、tor>using namespace std;/this struct represents an location.typedef struct int x;int y; Pair;class Gridprivate :Grid(const Grid& g);public:Pair * m_data;const int m_width; /grid widthconst int m_height; /grid heightint * m_adjacent; /memory arra
37、y/constructor with width and height of the grid.Grid(int x, int y):m_width(x), m_height(y) m_data = new Pairx*y; memset(m_data, 0, x*y *sizeof(Pair); m_adjacent = new intx*y; memset(m_adjacent, -1, x*y *sizeof(int);/free resourceGrid() de
38、lete m_data; delete m_adjacent;int Bin2One(int x, int y) return y*m_width + x;Pair One2Bin(int index) Pair p; p.x = index % m_width; p.y = index / m_width; return p;/this method is used to get or set the item of the &am
39、p; item(int x, int y) return m_datax+ y*m_width.x;/dynamic program main method, it recursively select the next location from the adjacents according to the getCap(const Pair & loc) /this array is used to storage the priority of four adjacents. int
40、 value4 = 0; /this array is used to access four adjacents according to current location. int mask42 = -1,0,0,1,1,0,0,-1/*x_coordinate, y_coordinate*/ ; /now, we start to deal with four adjacents. for (int i = 0; i < 4;
41、 i+) /make sure current location has four adjacents if (loc.x + maski0 >= 0 && loc.x + maski0 < m_width && loc.y + maski1 >= 0 && loc.y + maski1 < m_height)
42、0; /if the toy in the adjacent can hold current one. int current_toy = (m_dataBin2One(loc.x, loc.y).x > 0)?m_dataBin2One(loc.x, loc.y).x:m_dataBin2One(loc.x, loc.y).y; if ( item(loc.x + maski0, loc.y + maski1) >
43、; current_toy/item(loc.x , loc.y) | item(loc.x + maski0, loc.y + maski1) = 0)/when the adjacent has no toy. Pair adjacent; adjacent.x = loc.x + maski0; ad
44、jacent.y = loc.y + maski1; m_dataBin2One(adjacent.x, adjacent.y).y = current_toy; valuei = getCap(adjacent); int sum = 0; for (int i = 0; i < 4;
45、 i+) sum += valuei; /when all adjacents is less than current. if (sum = 0) return item(loc.x , loc.y); else int index = 0;
46、; int current_max = valueindex; int select = 0; for (int index = 0; index < 4; index+) if (current_max < valueindex) current_max = valueindex;
47、 select = index; m_adjacentBin2One(loc.x, loc.y) = Bin2One(loc.x + maskselect0, loc.y + maskselect1); return current_max + item(loc.x , loc.y); /this method drives the clas
48、svoid run() Pair loc; loc.x = 0; loc.y = 0; for (int i = 0; i < m_width*m_height; i+) m_datai.y = m_datai.x; cout << "total mark=" << this->getCap(loc) << endl;/d
49、isplay the gridvoid displayGrid() for (int i =0 ; i < this->m_height; i+) for (int j = 0; j < this->m_width; j+) cout << " " << this->m_datai*m_width + j.x;
50、160; cout << endl; /display the routine.void print() int current, next, out ; current = 0; next = m_adjacentcurrent; out = m_datacurrent.x; while (next != -1) cout &l
51、t;< " " << out ; current = next; next = m_adjacentcurrent; out = m_datacurrent.x; cout << " " << out ;int _tmain(int argc, _TCHAR* argv)ifstream in("input.txt");int x,y,
52、k, value;in >> x >> y ;Grid * grid = new Grid(y, x);value = 0;/this block initializes the grid items with ifstream. while (true) if (in.eof() break; in >> k;
53、60; grid->item(value%grid->m_width, value/grid->m_width) = k; value+;grid->displayGrid();grid->run();/donegrid->print();cin >>x;delete grid;grid = NULL;in.close();return 0;/ Snake.cpp : 定义控制台应用程序的入口点。/This program is used to collect the most mark and o
54、utput the routine./by nwpu043814/date:20100509#include "stdafx.h"#include <iostream>#include <fstream>#include <vector>using namespace std;/this struct represents an location.typedef struct int x;int y; Pair;class Gridprivate :Grid(const Grid& g);public:Pair * m_data;
55、const int m_width; /grid widthconst int m_height; /grid heightint * m_adjacent; /memory array/constructor with width and height of the grid.Grid(int x, int y):m_width(x), m_height(y) m_data = new Pairx*y; memset(m_data, 0, x*y
56、*sizeof(Pair); m_adjacent = new intx*y; memset(m_adjacent, -1, x*y *sizeof(int);/free resourceGrid() delete m_data; delete m_adjacent;int Bin2One(int x, int y) return y*m_width + x;Pair One2Bin(int index) Pair p; p.
57、x = index % m_width; p.y = index / m_width; return p;/this method is used to get or set the item of the & item(int x, int y) return m_datax+ y*m_width.x;/dynamic program main method, it recursively select the next location from the adjacents according
58、 to the getCap(const Pair & loc) /this array is used to storage the priority of four adjacents. int value4 = 0; /this array is used to access four adjacents according to current location. int mask42 = -1,0,0,1,1,0,0,
59、-1/*x_coordinate, y_coordinate*/ ; /now, we start to deal with four adjacents. for (int i = 0; i < 4; i+) /make sure current location has four adjacents if (loc.x + maski0 >= 0 && loc.x + maski0 < m
60、_width && loc.y + maski1 >= 0 && loc.y + maski1 < m_height) /if the toy in the adjacent can hold current one. int current_toy = (m_dataBin2One(loc.x, loc.y).x > 0)?m_
61、dataBin2One(loc.x, loc.y).x:m_dataBin2One(loc.x, loc.y).y; if ( item(loc.x + maski0, loc.y + maski1) > current_toy/item(loc.x , loc.y) | item(loc.x + maski0, loc.y + maski1) = 0)/when the adjacent has no toy.
62、0; Pair adjacent; adjacent.x = loc.x + maski0; adjacent.y = loc.y + maski1; m_dataBin2One(adjacent.x, adjacent.y).y = current_toy; valuei = getCap(ad
63、jacent); int sum = 0; for (int i = 0; i < 4; i+) sum += valuei; /when all adjacents is less than current. if (sum = 0)
64、; return item(loc.x , loc.y); else int index = 0; int current_max = valueindex; int select = 0; for (int index = 0; index < 4; index+)
65、0; if (current_max < valueindex) current_max = valueindex; select = index; m_adjacentBin2One(loc.x, loc.y) = Bin2One(loc
66、.x + maskselect0, loc.y + maskselect1); return current_max + item(loc.x , loc.y); /this method drives the classvoid run() Pair loc; loc.x = 0; loc.y = 0; for (int i = 0; i < m_width*m_height; i+)
67、; m_datai.y = m_datai.x; cout << "total mark=" << this->getCap(loc) << endl;/display the gridvoid displayGrid() for (int i =0 ; i < this->m_height; i+) for (int j = 0; j < this->m_wid
68、th; j+) cout << " " << this->m_datai*m_width + j.x; cout << endl; /display the routine.void print() int current, next, out ; current = 0; next = m_adjacentcurrent; out = m_datacurrent.x; while (next != -1) &
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 物联网系统定制与开发合同
- 水电安装承包合同样本
- 聘用合同聘请合同
- 2025年浙科版选修2地理上册阶段测试试卷
- 融资租赁回租合同
- 员工试用期劳动合同范本
- 月嫂公司服务合同范本
- 2025年人教五四新版九年级历史下册月考试卷含答案
- 2025商品房买卖合同3
- 2025企业合同管理表格
- 确定项目干系人(表格)
- 渠道管理就这样做
- 大客户销售这样说这样做
- 精装修样板房房屋使用说明
- 乔迁新居结婚典礼主持词
- 小学四年级数学竞赛试题(附答案)
- 鲁科版高中化学必修2全册教案
- 《病理学基础》知识考核试题题库与答案
- 人口分布 高一地理下学期人教版 必修第二册
- 四年级上册英语试题-Module 9 Unit 1 What happened to your head--外研社(一起)(含答案)
- 子宫内膜异位症诊疗指南
评论
0/150
提交评论