0

So I have made the following program successfully that will allow the user to punch in a number(between 1 to 12) and then tell the user after how many tries did that did the two dice roll the number originally typed, successfully. So if the person types 7. it will do the random roll the first time if the two dice total is 5 it will display..."Result of Throw 1 : 3 + 2" ..etc

But for some reason when I do it, it takes over 1000s of turns before 7 pops up as a result, finishing the program. odds for dice should around 1/12 not 1/1000 so I know I am coding something wrong. If anyone can help me figure out what is wrong, that would be great.

Here is my code so far...

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

int main(void){

int sought;
int roll1 = 7;
int roll2 = 7;
int minAmount = 0;
int maxAmount = 6;
int counter = 0;

printf("Dice Thrower\n");
printf("==============\n");
printf("Total Sought : ");
scanf("%d", &sought);
while (sought > 12){
        printf("Bad Input! Try Again!\n");
        printf("Total Sought : ");
        scanf("%d", &sought);
        }

while (sought != roll1 + roll2){
counter++;
srand(time(NULL));
roll1 = minAmount + rand() % (maxAmount + 1 - minAmount);
roll2 = minAmount + rand() % (maxAmount + 1 - minAmount);
printf("Result of Throw %d : %d + %d\n", counter, roll1, roll2);
}
printf("You got your total in %d throws!\n", counter);
}
timrau
  • 22,578
  • 4
  • 51
  • 64
Adeel Anwar
  • 729
  • 1
  • 5
  • 8
  • 9
    [**Only call `srand` once.**](http://stackoverflow.com/questions/7343833/srand-why-call-only-once) – Oliver Charlesworth Mar 19 '13 at 00:23
  • 2
    a similar question has been asked many times before, in many forms. Please search.... – Mitch Wheat Mar 19 '13 at 00:23
  • possible duplicate of [Why do I always get the same sequence of random numbers with rand()?](http://stackoverflow.com/questions/1108780/why-do-i-always-get-the-same-sequence-of-random-numbers-with-rand) – EdChum Mar 19 '13 at 08:42

1 Answers1

3

You keep calling srand() for each dice roll. That is, you initialize the random seed using current time for each row. Thus, the result only changed once per 1 second (not once per roll).

Move srand(time(NULL)) to the front of your while loop.

timrau
  • 22,578
  • 4
  • 51
  • 64