ランダム関数の内部メカニズム
1.種はすべて1から
2.srand手動入力シード
3.time関数を使用してシードを自動的に設定する
- #include
-
- extern int rand0(void);
-
- int main(void){
- int count;
-
- for(count=0;count<5;count++){
- printf("%d
",rand0());
- }
- getchar();
- }
- #include
- 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
-
- extern int rand1(void);
- extern void srand1(unsigned int x);
-
- int main(void){
- int count;
- unsigned seed;
-
- printf("Please enter your choice:
");
- while(scanf("%u",&seed) == 1){ //
- srand1(seed);
- for(count=0;count<5;count++){
- printf("%hd
",rand1());
- }
- printf("Please enter again ,q to quit
");
- }
- printf("Done
");
- 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
- #include
-
- 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
",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;
- }