简体   繁体   中英

Function inside a function not working

I have a function to generate random number in C. It works fine when I call it in main() function. But when I try to call it inside another function definition it is returning same number again and again. Please help. I am unable to understand the reason for 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 as the output repeatedly' 
  }

As the following test program shows, both your functions work just fine, except you always use the same randome seed, so everytime you run this program, it will give you the same result. You could remove the comment mark before srand() to fix this 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));
    for (i = 0; i < 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 
i = 0 : 8 3
i = 1 : 7 7
i = 2 : 9 1
i = 3 : 3 7
i = 4 : 2 5
i = 5 : 4 6
i = 6 : 3 5
i = 7 : 9 9
i = 8 : 6 7
i = 9 : 1 6

This test program could be used to show that those two functions will give the 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);
    for (i = 0; i < 10; i++) {
        x=rand_range(0,10);
        printf("i = %d : %d\n", i, x);
    }

    printf("\n\n");

    srand(1);
    for (i = 0; i < 10; i++) {
        x=rand_slot(10);
        printf("i = %d : %d\n", i, x);
    }

    return 0;
}

Run result:

$ ./a.out 
i = 0 : 8
i = 1 : 3
i = 2 : 7
i = 3 : 7
i = 4 : 9
i = 5 : 1
i = 6 : 3
i = 7 : 7
i = 8 : 2
i = 9 : 5


i = 0 : 8
i = 1 : 3
i = 2 : 7
i = 3 : 7
i = 4 : 9
i = 5 : 1
i = 6 : 3
i = 7 : 7
i = 8 : 2
i = 9 : 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM