Rand() returning the same value even with the inclusion of srand((unsigned)time(NULL)

Asked

Viewed 180 times

-1

Why the function scrolled below always returns the same values when called multiple times, although 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 of an exit:

13
13
13
--------------------------------

1 answer

1

Your mistake is that you are casting a seed several times, put srand in the 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);
}

Browser other questions tagged

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