jeudi 6 avril 2017

Creating a random integer is always outputting the same number

I'm trying to create a random integer using the following function:

static unsigned int random(int min, int max)
{
    double scaled = (double)rand() / RAND_MAX;

    return (max - min + 1) * scaled + min;
}

Then I'm trying to assign the integer like this:

int main()
{
    int playerScore, compScore = 0;
    int i;

    for (i = 0; i < 3; i++)
    {
        playerScore += random(0, 5);
        compScore += random(0, 5);
    }
    printf("Player score: %d\nComputer Score: %d\n", playerScore, compScore);
    return 0;
}

However when I compile and run I get the following output:

Player score: 32780
Computer Score: 7
e@ubuntu:~/bin/c/practice$ ./randtest
Player score: 32781
Computer Score: 7
e@ubuntu:~/bin/c/practice$ ./randtest
Player score: 32780
Computer Score: 7
e@ubuntu:~/bin/c/practice$ ./randtest
Player score: 32779
Computer Score: 7
e@ubuntu:~/bin/c/practice$ ./randtest
Player score: 32781
Computer Score: 7

This doesn't make any sense to me seeing as I only assign random numbers 0-5 three times to the variables, what am I doing wrong?




Aucun commentaire:

Enregistrer un commentaire