1

So, I'm currently reading a book about C and, in an exercise, I should do a program that would get input from user (a number between 1 and 12) and would "roll" that number of dice, and then display the results. The problem is, when it randomizes the dice numbers, all results are exactly the same. And I did use "srand((unsigned)time(NULL))" to seed. What could possibly be going wrong?

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

int throw(void);

int main()
{
    int many,x,sum;
    sum = 0;

    puts("R O L L ' E M !");
    type:
    printf("How many dice would you like to roll (1 - 12)? ");
    scanf("%d",&many);
    if(many>12) {
        puts("You can roll up to 12 dice!");
        goto type;}
    if(many<1) {
        puts("You need to roll at least one die!");
        goto type;}

    int num[many];

    printf("\nRolling %d...\n",many);
    puts("Here they come!");

    printf(" ");        
    for(x=0;x<many;x++)     /* Shows which die it is */
    {
        if(x>=9)
            printf("%d  ",x+1);
        else
            printf(" %d  ",x+1);
    }
    putchar('\n');
    for(x=0;x<many;x++)     /* Thingy to illustrate the dice */
        printf("+---");
    puts("+");
    for(x=0;x<many;x++)     /* Shows dice results */
    {
        num[x] = throw();
        printf("| %d ",num[x]);
        sum = sum + num[x];
    }
    puts("|");
    for(x=0;x<many;x++)       /* Thingy to illustrate the dice */
        printf("+---");
    puts("+");

    printf("Total = %d",sum);    /* Shows total */
    return(0);
    }

int throw(void)  /* "Throws" the dice, by randomizing a number between 1 and 6 */
{
    int n;

    srand((unsigned)time(NULL));  /* seed */
    n = rand() % 6 + 1;           /* randomizes and limits from 1 to 6 */
    return(n);                      
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190

2 Answers2

2

You are calling srand before for each call to rand. srand initializes the algorithm with a seed. Probably because of the short time between the calls, the timestamp is the same, therefore the seed. As a result, you reinitialize the algorithm with the same value, therefore producing the same sequence of numbers. The solution is to call srand only once per thread.

Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
1

you have to use srand() just one time at the beginning of your program, otherwise the rand() function uses the same seed for all the calls since srand is called many times in a very small time lapse, shorter than a second and the seed remains the same for all the calls..

woggioni
  • 1,261
  • 1
  • 9
  • 19