Challenge 2 - rand() not working

0 Lucca Nomdefazlol · August 25, 2014
I tried to make the second challenge thingy, and everything works other than the rand() statement. For some reason the first one is always 17 and the second one is always 16, what did I do wrong?


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

int main()
{
    int dice1, dice2, i;
    char answer;
    dice1 = dice2 = 0;


    for(i = 0; i < 3; i++){
        dice1 += ( rand()%6 ) + 1;
    }

    printf("Total was: %d\n", dice1);

    puts("Next roll will be (H)igher, (L)ower or the (S)ame?");
    scanf(" %c", &answer);

    for(i = 0; i < 3; i++){
        dice2 += ( rand()%6 ) + 1;
    }

    if( ( (dice1 > dice2) && (tolower(answer) == 'l') ) || ( (tolower(answer) == 'h') && (dice1 < dice2) )  || ( (tolower(answer) == 's') && (dice1 == dice2) ) ){
        puts("Lucky guess?");
    }else{
        puts("HAHA YOU SUCK HAHAHHAHAHAHAHHAHAHAHAHHAHAHAHHA");
    }

    printf("The second roll total was:%d\n", dice2);
}



Post a Reply

Replies

Oldest  Newest  Rating
+4 Bucky Roberts · August 25, 2014
Different computers generate random numbers in different ways. If you keep getting the same numbers over and over again, it's because your computer is using the same "random number" formula every time.

What you can do to fix this is use srand() to add a new custom variable to the computer's random number generator. This will cause the results to be different every time. I made you a quick example:

http://pastebin.com/mtUxgYbk

Don't forget to include the time header

#include <time.h>
0 Rolandas Seacret · August 25, 2014
or you can do without including "time.h" just put  srand((unsigned)time(NULL)); in the beginning of your program and it will work :)
  • 1

C

107,322 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator