0

Newbie here!

I wrote a simple two dice rolling code. The srand() function doesn't work until I put it into the main() function. Why is that? At first I thought that with every dice_roll funtion call the srand() would do it's job! Insted I get doubles every time. As I said I fixed it when the srand() got into main() but I have a hard time understanting the logic! Here's my code(before solving the problem!!)

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

int dice_roll();

main(int argc, char* argv[]){
    int dice_1,dice_2;
        
    dice_1=dice_roll();
    dice_2=dice_roll();
    printf("%d\n",dice_1);
    printf("%d",dice_2);    
}

int dice_roll(){
    srand(time(NULL));
    return (rand() % 6 +1);
}
Luuk
  • 12,245
  • 5
  • 22
  • 33
V_88
  • 1
  • Please [edit] to tag the language you're using. (C or C++, I would assume; I don't personally know either well enough to tell the difference.) – CrazyChucky Jul 23 '22 at 15:55
  • 5
    It is explained in the [docs of srand](https://cplusplus.com/reference/cstdlib/srand/) then after doing `srand(1)` the first call to `rand()` will always give the same value. So you need to do the srand 1 time in your main (before rolling the dice). For a better explanation see the link, which has a nice example. – Luuk Jul 23 '22 at 16:03

0 Answers0