srand函数将返回相同的值 [英] srand function is returning same values

查看:88
本文介绍了srand函数将返回相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,伙计们看看这个节目。

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("\nYou won!\n");
        return true;
    }

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

    point = sum;

    printf("\n\nYour point is: %d", point);

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

    }while(sum != point);

    if(sum == point)
    {
        printf("\nYou 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("\nPlay Again? ");
        scanf("%c", &c);

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

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

    return 0;
}

srand函数返回保持,相同的值3〜4次,Y是什么?

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

我想不同的值,每次当我掷骰子,复制code和运行它,看看我的意思

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

推荐答案

srand()函数用于设置种子为rand()函数的函数。你在这里做的是设置种子当前时间每兰特(前)调用,而如果所谓的速度不够快,就会让你相同的值(因为它会恢复到相同的种子,而如果速度不够快会同一时间值)。

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).

你会想要做的是调用函数srand()一次,程序启动时(在你的main()函数的开始)

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

然后调用rand()你想有一个随机数,就像你正在做的目前每一次,但没有调用srand()函数每次。

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

这篇关于srand函数将返回相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆