mly128 mly128 - 4 months ago 23
C Question

user-defined function for random number generator in C output incorrect

For this program we have to create a user defined function to return 25 random variables from a value of 60-100, but when I run the program all 25 values are the same. I'm pretty new at programming and I think the error resided in where the user-function is defined, because I think instead of running the variable 25 times, its just running once and printing that first value 25 times. But I don't know how to actually go about fixing it :(

#include <stdlib.h>
#include <time.h>

int get_value (int Random);

int main ()
srand(time(NULL));//to randomize the number after each run
int Random = rand()%40+60;

printf("These are the temperatures for the day\n");
int temp[25], i;
for (i=0; i<25; i++)
temp[i] = Random;
printf("%d\n" ,temp[i]);
return 0;

int get_value (int Random)
Random = rand() % 40 + 60;


That's because get_value() has not returned anything. The Random argument is a copy of the Random which you (might have) passed. It's legitimate to overwrite a (non-const) function arguement, but it won't find it's way way to the caller. The second problem is that you never call this function anyway, you just repeat the first random number you generated.

I suggest you rewrite the function like this

int get_value (void)
    return rand()%41+60;        // range 60 to 100

and call it like this

temp[i] = get_value();