6. Write a program that generates 1,000 random numbers in the range 1-10. Don’t save or print the numbers, but do print how many times each number was produced. Have the program do this for ten different seed values. Do the numbers appear in equal amounts? You can use the functions from this chapter or ANSI C rand() and srand() functions, which follow the same format that our function do. This is one way to test randomness of a particular random-number generator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include<time.h> #include<stdlib.h> #include<stdio.h> int main(void) { int i; int array[10]; srand(time(NULL)); for( i = 0 ; i < 10 ; i++) array[i] = 0; for( i = 0 ; i < 1000 ; i++) array[rand()%10]++; for( i = 0 ; i < 10 ; i++) printf("%4d = %4d \n",i+1,array[i]); return 0; } |
補充:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { int x, y; int random[1000]; int count[10] = {0,0,0,0,0,0,0,0,0,0}; unsigned seed; puts("Please enter the seed:(q to quit)"); while(scanf("%u", &seed) == 1) { srand(seed); // 這邊要種 seed for (x = 0; x <= 999; x++) random[x] = rand()%10 ; // 這樣就指定完一千個亂數了 for (x = 0; x < 10; x++) for (y = 0 ; y <= 999; y++) if(random[y] == x) count[x]++; for (x = 0; x < 10; x++) printf("The element: %d , has been counted for %d times\n",x+1 , count[x] ); } system("pause"); return 0; } |