1

所以,我目前正在阅读一本关于 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);                      
}
4

2 回答 2

2

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

于 2013-09-24T06:11:46.613 回答
1

您必须在程序开始时只使用一次 srand() ,否则 rand() 函数对所有调用使用相同的种子,因为 srand 在非常短的时间间隔内被多次调用,不到一秒并且所有电话的种子都保持不变..

于 2013-09-24T06:12:43.667 回答