1.种子都从1开始
- #include<stdio.h>
- extern int rand0(void);
- int main(void){
- int count;
- for(count=0;count<5;count++){
- printf("%d\n",rand0());
- }
- getchar();
- }
- #include<stdio.h>
- static unsigned int next = 1;//本系统中,int和long的长度是一样的
- int rand0(void){ //计算机不具有自发性,这是一个伪随机数,可以预测数字的实际顺序
- next = next * 1103515245 + 12345;//next的值可能会溢出,但是没有关系,因为当超过最大值时,会循环到负数
- return (unsigned int)(next/65535)%32768;//而我们最后的返回值被转换为unsigned int类型了
- }
2.srand手动输入种子
- #include<stdio.h>
- extern int rand1(void);
- extern void srand1(unsigned int x);
- int main(void){
- int count;
- unsigned seed;
- printf("Please enter your choice:\n");
- while(scanf("%u",&seed) == 1){ //手动设置种子
- srand1(seed);
- for(count=0;count<5;count++){
- printf("%hd\n",rand1());
- }
- printf("Please enter again ,q to quit\n");
- }
- printf("Done\n");
- return 0;
- }
- static unsigned long int next = 1; //rand和srand共享一个内部链接静态变量
- int rand1(void){
- next = next * 1103515245 + 12345;
- return (unsigned int)(next/65536)%32768;
- }
- void srand1(unsigned int seed){
- next = seed;
- }
3.使用time函数自动设置种子
- #include<stdio.h>
- #include<time.h>
- extern int rand2(void);
- extern void srand2(unsigned int seed);
- int main(void){
- int count;
- srand2((unsigned int)time(0));//time可以返回系统时间返回值为数值类型,传送空指针即可
- for(count=0;count<5;count++){
- printf("%d\n",rand2());
- }
- getchar();
- return 0;
- }
- static unsigned long int next = 1;
- int rand2(void){
- next = next * 1103515245 + 12345;
- return (unsigned int)(next/65536)%32768;
- }
- void srand2(unsigned int seed){
- next = seed;
- }