Rand()在C中并不是唯一的

Jam*_*are 1 c random

我正在使用rand()函数生成随机巧克力.即使我播种了时间,rand()总是给我相同的数字,我不知道如何解决它?

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


int main() {
    /* Seed the random number generator */
    srand48(time(0));
    double t=rand()%5;
    printf("Your selected chocolate will be: \n");
    if(t==0){
        printf("Caramel\n");
    }
    else if(t==1){
        printf("Milk\n");
    }
    else if(t==2){
        printf("Sweet\n");
    }
    else if(t==3){
        printf("Semi-sweet\n");
    }
    else {
        printf("Dark\n");
    }

    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Gov*_*mar 5

正如其他人在评论中指出的那样,这个功能srand48没有种子rand; 它的种子lrand48和相关功能.从手册页:

srand48(),seed48()和lcong48()函数是初始化函数,在使用drand48(),lrand48()或mrand48()之前应该调用其中一个函数.函数erand48(),nrand48()和jrand48()不需要首先调用初始化函数.

您需要srand使用参数调用以将函数time(0)播种rand到当前系统时间.

另外,为什么使用该类型double来存储从中返回的值rand?使用足以包含RAND_MAX在系统中的整数类型; 通常shortint.