Dice roll i get same random numbers..

 Alok Pandey · June 28, 2015 i made the following code , yet i always get same random numbers for dice roll challenge , please help me or correct me . thanx #include #include #include #include #include int main(){    char high = 'h';    char low = 'l';    char same = 's';    char choice;    int diceroll ,i ,j;    int total = 0;    int total1 = 0;     for (i = 1 ; i<=3; i++)     {       diceroll=( rand()%6 )+1; total = total + diceroll;     }printf("%d is the sum of number of three dices on first roll\n ",total);printf("Enter h (high) , l (low) or s(same) to guess next number:  \n");     scanf("%c",&choice);     diceroll = 0;     for (j = 1 ; j<=3; j++)     {       diceroll=( rand()%6 )+1;       total1 = total1 + diceroll;     }     switch (choice){ case 'h':    if(total1>total)         printf("%d is new total congrats you won", total1);    else        printf("%d is new total You loose", total1);        break; case 'l':    if(total1

Replies

 Justin Senato · June 28, 2015 Hi Alok, I just started programming 6 months ago so I apologize I can't give you all the technical details around this.Try adding srand(time(0)); before calling rand(). Place it outside of the loop. When using rand(), it generates its numbers based on a seed, by using time(0) as the seed, it will use a seed based on the time down to the second. So every time you run the program the numbers will be different. The reason you want to use srand(time(0)) outside of the loop rather than inside is because the computer will run every iteration of your loop in less than one second so it will do something like reset the seed to the same thing each time and give you all of the exact same numbers ( i think). Regardless, try to change your code to look like this and see if it works properly.srand(time(0));for (i = 1 ; i<=3; i++){diceroll=( rand()%6 )+1;total = total + diceroll;} Alok Pandey · June 28, 2015 finally worked.. Thanx for the help  srand (time(0));     for (i = 1 ; i<=3; i++)     {       diceroll=( rand()%6 )+1; total = total + diceroll;     }printf("%d is the sum of number of three dices on first roll\n ",total);printf("Enter h (high) , l (low) or s(same) to guess next number:  \n");     scanf("%c",&choice);     diceroll = 0;     srand (time(0));     for (j = 1 ; j<=3; j++)     {       diceroll=( rand()%6 )+1;       total1 = total1 + diceroll;     } Homer Simpson · June 28, 2015 srand(time(0));Call that before calling rand.Here's what it does. http://www.cplusplus.com/reference/cstdlib/srand/
• 1

C

129,748 followers