c - Function inside a function not working -
i have function generate random number in c. works fine when call in main() function. when try call inside function definition returning same number again , again. please help. unable understand reason this.
double uniform_deviate ( int seed ) { return seed * ( 1.0 / ( rand_max + 1.0 ) ); } int rand_range(int min_n, int max_n) { return min_n + uniform_deviate ( rand() ) * ( max_n - min_n ); } int rand_slot(int num_values) { int x; x=rand_range(0,num_values); return x; } void main() { int x,y; x=rand_range(0,10) - 'works fine' y=rand_slot(6) - 'gives 5 output repeatedly' }
as following test program shows, both functions work fine, except use same randome seed, everytime run program, give same result. remove comment mark before srand() fix problem.
#include <stdio.h> #include <stdlib.h> #include <time.h> double uniform_deviate ( int seed ) { return seed * ( 1.0 / ( rand_max + 1.0 ) ); } int rand_range(int min_n, int max_n) { return min_n + uniform_deviate ( rand() ) * ( max_n - min_n ); } int rand_slot(int num_values) { int x; x=rand_range(0,num_values); return x; } int main() { int x,y,i; //srand(time(null)); (i = 0; < 10; i++) { x=rand_range(0,10); y=rand_slot(10); printf("i = %d : %d %d\n", i, x, y); } return 0; } run result:
$ ./a.out = 0 : 8 3 = 1 : 7 7 = 2 : 9 1 = 3 : 3 7 = 4 : 2 5 = 5 : 4 6 = 6 : 3 5 = 7 : 9 9 = 8 : 6 7 = 9 : 1 6 this test program used show 2 functions give same number list:
#include <stdio.h> #include <stdlib.h> #include <time.h> double uniform_deviate ( int seed ) { return seed * ( 1.0 / ( rand_max + 1.0 ) ); } int rand_range(int min_n, int max_n) { return min_n + uniform_deviate ( rand() ) * ( max_n - min_n ); } int rand_slot(int num_values) { int x; x=rand_range(0,num_values); return x; } int main() { int x,i; srand(1); (i = 0; < 10; i++) { x=rand_range(0,10); printf("i = %d : %d\n", i, x); } printf("\n\n"); srand(1); (i = 0; < 10; i++) { x=rand_slot(10); printf("i = %d : %d\n", i, x); } return 0; } run result:
$ ./a.out = 0 : 8 = 1 : 3 = 2 : 7 = 3 : 7 = 4 : 9 = 5 : 1 = 6 : 3 = 7 : 7 = 8 : 2 = 9 : 5 = 0 : 8 = 1 : 3 = 2 : 7 = 3 : 7 = 4 : 9 = 5 : 1 = 6 : 3 = 7 : 7 = 8 : 2 = 9 : 5
Comments
Post a Comment