Random number generation in a function is always equal - C

Asked

Viewed 53 times

1

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

int aleatorio(){
    srand(time(NULL));
    return rand() % 10 + 1;
}

main(){
    int numero1 = aleatorio();
    int numero2 = aleatorio();
    printf("%d %d",numero1, numero2);
}

I have a project to do and I will use a function that generates random numbers, so I decided to go doing tests on it and the function always returns the same number, even if I have put the seed inside Rand(). Even if the seed has been placed within a function, the generated number should not be different already as each time I call it a new seed is placed. I’d like you to help me.

  • basically by the fact that you do srand twice with the same value. Do srand only once, otherwise you reset Seed to each function call (ie two calls on the same time() will always result the same value.

  • 3

    Retire srand(time(NULL));of its function. It must be executed only once at the beginning of the program and not every call of the function aleatorio.

2 answers

3


Your code calls the function aleatorio() two times next. Within this function has a srand, which serves to initialize the sequence of random numbers (the "seed", or "Seed").

It occurs that very likely, most of the times we call the function then the time() return the same value in the two calls, effectively "resetting" the sequence to always start from the same number.

Ideally you only make one srand(time()) once in the code, which solves this and other possible problems that may arise from changing the Seed frequently.

See how the code looks after modified to use the srand once:

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

int aleatorio(){
    return rand() % 10 + 1;
}

main(){
    srand(time(NULL));
    int numero1 = aleatorio();
    int numero2 = aleatorio();
    printf("%d %d",numero1, numero2);
}

See working on IDEONE:

https://ideone.com/xzCdF2

1

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

int aleatorio(){
    return rand() % 10 + 1;
}

int main(){
    srand(time(NULL));
    int numero1 = aleatorio();
    int numero2 = aleatorio();
    printf("%d %d",numero1, numero2);
    return 0;
}

Place the Seed inside the main.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.