Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

c - srand function is returning same values

Hey guys take a look at this program.

/* The craps game, KN king page 218 */

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

int roll_dice(void);
bool play_game(void);

int roll_dice(void)
{
    int roll;

    getchar();
    srand((unsigned) time(NULL));

    roll = rand() % 13;

    if(roll == 0)
    roll = roll + 1;

    return roll;
}

bool play_game()
{
    int sum = 0, wins = 0, loss = 0, point;

    sum = roll_dice();

    printf("You rolled: %d", sum);

    if(sum == 7 || sum == 11)
    {
        printf("
You won!
");
        return true;
    }

    if(sum == 2 || sum == 3 || sum == 12)
    {
        printf("
You lost!!");
        return false;
    }

    point = sum;

    printf("

Your point is: %d", point);

    do
    {
        sum = roll_dice();
        printf("
You rolled: %d", sum);

    }while(sum != point);

    if(sum == point)
    {
        printf("
You won!!!");
        return true;
    }

}

int main()
{
    char c, wins = 0, losses = 0;
    bool check;

    do
    {
        check = play_game();

        if(check == true)
          wins++;

        else if(check == false)
          losses++;

        printf("
Play Again? ");
        scanf("%c", &c);

    }while(c == 'Y' || c == 'y');

    printf("
Wins: %d      Losses: %d", wins, losses);

    return 0;
}

The srand function keeps returning, same value 3 or 4 times, y is that?

I want different values each time when i roll the dice, copy the code and run it to see what i mean

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

srand() is a function that sets the seed for the rand() function. What you are doing here is setting the seed to the current time before every rand() you call, which, if called fast enough, will get you the same value (since it will reset to the same seed, which if fast enough will be the same time value).

What you'll want to do is call srand() once, when the program starts (at the start of your main() function)

Then call rand() every time you want a random number, like you are doing currently, but without calling srand() every time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...