如何为每个玩家生成不同的随机数

如何为每个玩家生成不同的随机数

本文介绍了如何为每个玩家生成不同的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个玩家都获得相同的随机数! want我希望每个球员都得到不同的数字,因为他们掷骰子.这是代码:

Both players get the same random number! ّI want each player to get a different number since they are throwing dice.here is the code:

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

int roll_a_dice(void);

int main(int argc, const char *argv[])
{
    int flag;
    int answer1 = roll_a_dice();
    int answer2 = roll_a_dice();

    printf("Die 1 (rolled by player 1): %d\n", answer1);
    printf("Die 2 (rolled by player 2): %d\n", answer2);

    if (answer1>answer2) {
        printf("Player 1 is starting!\n");
        flag = 1;
    } else {
        printf("Player 2 is starting!\n");
        flag = 2;
    }

    printf("Goodbye!\n");

    return 0;
}

int roll_a_dice(void)
{
    int r;

    srand(time(NULL));
    r = 1 + rand() % 6;

    return r;
}

玩家正在掷骰子.因此编号必须为1-6.我该如何解决?

The players are throwing dice. So number has to be 1-6.How can I fix this?

推荐答案

srand ( time(NULL) );用于植入伪随机数生成器. time()的粒度为1秒,如果您每次调用roll_a_dice()函数时都为PNRG设置种子,那么对于在粒度周期内进行的所有调用,rand()最终将返回相同的 random 数字.

srand ( time(NULL) ); is used to seed the pseudo-random number generator. time() having a granularity of 1 second, if you seed the PNRG every time you call the roll_a_dice() function, for all the calls made within the granularity period, rand() will end up returning the same random number.

srand ( time(NULL) );roll_a_dice()函数中移出,仅在main()中调用一次.

Move the srand ( time(NULL) ); out of the roll_a_dice() function, call that only once in main().

这篇关于如何为每个玩家生成不同的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 16:18