rand () returning the same value even with the inclusion of srand ((unsigned) time (NULL) [duplicate]

-1

Why does the rolaData function below always return the same values when calling multiple times, even though seed srand ((unsigned) time (NULL)) has been initialized?

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

int rolaDados(int *a){
    srand((unsigned)time(NULL));
    int i = 0;
    int temp = 0;


    for(i=0;i<3;i++){
       temp += 1 + rand()%6;
    }
    return(temp);
}

void main(){
    int a=rolaDados(&a);
    int b=rolaDados(&b);
    int c=rolaDados(&c);

    printf("%d\n%d\n%d",a,b,c);
}

Example output:

13
13
13
--------------------------------
    
asked by anonymous 04.11.2018 / 20:30

1 answer

1

Your mistake is that you are launching a seed several times, put srand on main and see the result.

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

int rolaDados(){
    int i = 0;
    int temp = 0;

    for(i=0;i<3;i++){
       temp += 1 + rand() % 6;
    }

    return(temp);
}

void main(){
    srand(time(NULL));

    int a=rolaDados();
    int b=rolaDados();
    int c=rolaDados();

    printf("%d\n%d\n%d",a,b,c);
}
    
04.11.2018 / 20:38