Store random numbers in a variable in C

Asked

Viewed 356 times

1

Hello, I need to compare the random value of 2 dice thrown, and I would like to know how I can store the result of these numbers in the variables D1 and D2.

int d1, d2, n;

printf("Quantas vezes voce deseja jogar? ");
scanf("%d",&n);


for (int contador = 0; contador < n; contador++){
    printf("%d \n",rand() % 6);
    printf("%d \n",rand() & 6);

    if (d1 == d2){
        printf("Os dados deram iguais \n");
    } else if(d1 > d2){
        printf("D1 venceu \n");
    } else{
        printf("D2 venceu \n");
    }
}
  • To generate numbers with some degree of randomness it is convenient to initialize the seed with the function srand.

1 answer

0


Instead of directly printing the function values rand(), assign values to variables d1 and d2.

As Deitel quotes, in his book, when using the function srand() if we wish to randomize without the need to provide a seed each time, we can use a command such as:

srand(time(0));

Your code will look like this:

int main()
{
int d1, d2, n;

printf("Quantas vezes voce deseja jogar? ");
scanf("%d",&n);
srand( time(0));

for (int contador = 0; contador < n; contador++){
    d1 =  rand() % 6;
    d2 = rand() & 6;
    printf("%d \n",d1);
    printf("%d \n",d2);

    if (d1 == d2){
        printf("Os dados deram iguais \n");
    } else if(d1 > d2){
        printf("D1 venceu \n");
    } else{
        printf("D2 venceu \n");
    }
}
}
  • I’ve done that, but as I type the value of n, it always repeats the sequence of random numbers. For example if I type n = 2 the program returns 5 5 4 4, and always gets these values.

  • @Matheussantos test now, see if it works

  • 1

    Thank you very much, now he’s generating the numbers at random.

Browser other questions tagged

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