C++产生随机数

来源:互联网 发布:女生宿舍关系 知乎 编辑:程序博客网 时间:2024/05/23 01:10

我的模板

#include <cstdio>#include <cstdlib>#include <ctime>using namespace std;#define random(x) (rand()%x)int main(){    srand((unsigned)time(0));    for(int i=1;i<10;++i)        printf("%d\n",random(100));    system("pause");    return 0;} 

写模板的时候发现自己对变量的命名+缩写还不是太清楚,例如unsigned其实就是unsigned int:

在网上找了一下资料,如下:

名称

全称类型说明符

缩写类型说明符      

位数       

             范围

整型

int

int

16     

-32768+32767 

无符号整型

unsigned int 

unsigned

16

0 65,535 

短整型

short int 

short

16

-32768+32767 

无符号短整型     

unsigned short int    

unsigned short

16

0 65,535 

长整型

long int 

long

32

-2,147,483,648 2,147,483,647

无符号长整型     

unsigned long int     

unsigned long        

32      

04,294,967,295

 


别人写的思路加代码:


C语言/C++怎样产生随机数:这里要用到的是rand()函数, srand()函数,C语言/C++里没有自带的random(int number)函数。(1) 如果你只要产生随机数而不需要设定范围的话,你只要用rand()就可以了:rand()会返回一随机数值, 范围在0至RAND_MAX 间。RAND_MAX定义在stdlib.h, 其值为2147483647。例如:#include<stdio.h>#include<stdlib.h>void main(){       for(int i=0;i<10;i+)             printf("%d\n",rand());}(2) 如果你要随机生成一个在一定范围的数,你可以在宏定义中定义一个random(int number)函数,然后在main()里面直接调用random()函数:例如:随机生成10个0~100的数:#include<stdio.h>#include<stdlib.h>#define random(x) (rand()%x)void main(){     for(int x=0;x<10;x++)           printf("%d\n",random(100));}(3)但是上面两个例子所生成的随机数都只能是一次性的,如果你第二次运行的时候输出结果仍和第一次一样。这与srand()函数有关。 srand()用来设置rand()产生随机数时的随机数种子。在调用rand()函数产生随机数前,必须先利用srand()设好随机数种子(seed), 如果未设随机数种子, rand()在调用时会自动设随机数种子为1。上面的两个例子就是因为没有设置随机数种子,每次随机数种子都自动设成相同值1 ,进而导致rand()所产生的随机数值都一样。srand()函数定义 : void srand (unsigned int seed);通常可以利用geypid()或time(0)的返回值来当做seed如果你用time(0)的话,要加入头文件#include<time.h>例如:#include<stdio.h>#include<stdlib.h>#include<time.h>#define random(x) (rand()%x)void main(){     srand((unsigned)time(0));     for(int x=0;x<10;x++)           printf("%d\n",random(100));}这样两次运行的结果就会不一样了!!