c - Rand() 没有正确随机化

标签 c random

<分区>

所以,我目前正在阅读一本关于 C 语言的书,在练习中,我应该编写一个程序来获取用户的输入(1 到 12 之间的数字)并“掷”那个数量的骰子,并且然后显示结果。 问题是,当它随机化骰子数字时,所有结果都完全相同。我确实使用“srand((unsigned)time(NULL))”来播种。可能出了什么问题?

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

int throw(void);

int main()
{
    int many,x,sum;
    sum = 0;

    puts("R O L L ' E M !");
    type:
    printf("How many dice would you like to roll (1 - 12)? ");
    scanf("%d",&many);
    if(many>12) {
        puts("You can roll up to 12 dice!");
        goto type;}
    if(many<1) {
        puts("You need to roll at least one die!");
        goto type;}

    int num[many];

    printf("\nRolling %d...\n",many);
    puts("Here they come!");

    printf(" ");        
    for(x=0;x<many;x++)     /* Shows which die it is */
    {
        if(x>=9)
            printf("%d  ",x+1);
        else
            printf(" %d  ",x+1);
    }
    putchar('\n');
    for(x=0;x<many;x++)     /* Thingy to illustrate the dice */
        printf("+---");
    puts("+");
    for(x=0;x<many;x++)     /* Shows dice results */
    {
        num[x] = throw();
        printf("| %d ",num[x]);
        sum = sum + num[x];
    }
    puts("|");
    for(x=0;x<many;x++)       /* Thingy to illustrate the dice */
        printf("+---");
    puts("+");

    printf("Total = %d",sum);    /* Shows total */
    return(0);
    }

int throw(void)  /* "Throws" the dice, by randomizing a number between 1 and 6 */
{
    int n;

    srand((unsigned)time(NULL));  /* seed */
    n = rand() % 6 + 1;           /* randomizes and limits from 1 to 6 */
    return(n);                      
}

最佳答案

您在每次调用 rand 之前都调用了 srandsrand 使用种子初始化算法。可能是因为调用之间的时间很短,时间戳是相同的,因此是种子。结果,您使用相同的值重新初始化算法,从而产生相同的数字序列。解决方案是每个线程只调用一次 srand

关于c - Rand() 没有正确随机化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18974129/

相关文章:

c - c中的指针数组,访问原始数组

我可以执行驻留在数据段(ELF 二进制文件)中的代码吗?

algorithm - 预期运行时间与最坏情况运行时间

java - 将一个数均匀随机分成m份

java - 使用 getInt(int n) 方法获取 Java 的 RNG 种子

c++ - 在C++中生成随机非重复数数组

random - Lua math.random 不工作

c - Backspace 不删除字符,类似于 BASH

C 编程,使用 BUFSIZ、malloc 和 memset 的缺陷

c - 将数据添加到特定协议(protocol)的数据包中