Question

I can't seem to figure out why this is not working. I am trying to get these two void functions to generate randoms numbers when called in the main. I think the problem has to do with srand(time(NULL)); in the void function's. I think that when it gets called in the main and runs in the for loop, srand(time(NULL)); is not updated so it prints out the same number x times. numGen_10 should generate 1-10 and numGen_4 should generate 1-4 based on a variable.

What can I do to get the functions to output different random numbers each time the function is called?

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void numGen_10(int xOry, int* xRey);
void numGen_4(int num, int choice, int *choiceRe);


int main()
{
    int x;
    int num = 5;

    for (int i = 0; i < 3; i++)
    {
        numGen_10(x, &x);
        printf("val : %d \n", x);
    }

    printf("------------------------\n");

    for (int i = 0; i < 4; i++)
    {
        numGen_4(4, x, &x);
        printf("val2 : %d \n", x);
    }
    return 0;
}



void numGen_10(int xOry, int *xRey)
{
        srand(time(NULL));
        int r = rand() % 10 + 1;
        xOry = r;
        *xRey = xOry;
    return;
}

void numGen_4(int num, int choice, int *choiceRe)
{
    srand(time(NULL));
    choice = rand() % num + 1;
    *choiceRe = choice;
    return;
}
Was it helpful?

Solution

The random number generator is completely deterministic; it will always output the same sequence of numbers for any given seed. srand() seeds the random number generator. So by calling srand() with the time immediately before each call to rand(), and since your loops will take less than a second to execute, you'll always get the same random number (or maybe two if the time happens to change in the middle).

Try calling srand() once before entering the loops.

OTHER TIPS

Just for fun , add a delay of 1 second before each srand call when calling srand multiple times :

    sleep(1);
    /* or delay(1001); or usleep(500000);usleep(500000); based on availability */
    srand(time(NULL));

Additional to what others said about solving problem of srand I would like to add a remark about how you use pointers, calling your functions with x and &x is pointless, you can just call either with pointer only or with variable only:

calling with pointer :

void numGen_10(int* xRey); // prototype
void numGen_10(int *xRey) // function's body
{
    int r = rand() % 10 + 1;
    *xRey = r; 
    return;
}
numGen_4(4, &x); // use from the main function

calling with variable :

int numGen_10(int xRey); // prototype
int numGen_10(int xRey) //function's body 
{
    int r = rand() % 10 + 1;
    return r;
}
int y = numGen_4(4, x);  // use from the main function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top