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

标签 c random srand

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

#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。 我该如何解决这个问题?

最佳答案

srand ( time(NULL) ); 用于为伪随机数生成器提供种子。 time() 的粒度为 1 秒,如果每次调用 roll_a_dice() 函数时都播种 PNRG,则对于该粒度周期内进行的所有调用,rand() 最终将返回相同的随机数字。

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

关于c - 如何为每个玩家生成不同的随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36558716/

相关文章:

java - 这个算法可以找到一个系列的无穷大之和吗?

C 指向结构的双/三指针

python 如何再次绘制一个变量,如果它与另一个变量相同

c - 如何在多个进程中同时生成随机数?

math - 避免随机生成的减法问题中的偏差

c - srand()——为什么只调用一次?

c++ - fork进程之间的随机数是相同的

c - 优先规则 - 使用括号和除法与 srand 获取 float 时出现问题

c - 在其他字符的字符串中查找数字的最有效方法是什么?

c - 如何在 6 位二进制数之前添加 0,使其成为 7 位