有没有一个函数生成一个随机int数在C?或者我必须使用第三方库?


当前回答

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

//generate number in range [min,max)
int random(int min, int max){
    int number = min + rand() % (max - min);
    return number; 
}

//Driver code
int main(){
    srand(time(NULL));
    for(int i = 1; i <= 10; i++){
        printf("%d\t", random(10, 100));
    }
    return 0;
}

其他回答

在我最近的应用程序中,我遇到了一个严重的伪随机数生成器问题:我多次通过Python脚本调用我的C程序,并使用以下代码作为种子:

srand(time(NULL))

然而,由于:

Rand将生成相同的伪随机序列,在srand中给出相同的种子(参见man srand); 如前所述,time函数每秒只会变化:如果应用程序在同一秒内运行多次,time每次都会返回相同的值。

我的程序生成了相同的数字序列。 你可以做三件事来解决这个问题:

mix time output with some other information changing on runs (in my application, the output name): srand(time(NULL) | getHashOfString(outputName)) I used djb2 as my hash function. Increase time resolution. On my platform, clock_gettime was available, so I use it: #include<time.h> struct timespec nanos; clock_gettime(CLOCK_MONOTONIC, &nanos) srand(nanos.tv_nsec); Use both methods together: #include<time.h> struct timespec nanos; clock_gettime(CLOCK_MONOTONIC, &nanos) srand(nanos.tv_nsec | getHashOfString(outputName));

选项3确保了你(据我所知)最好的种子随机性,但它可能只会在非常快速的应用中产生差异。 在我看来,选择2是一个安全的赌注。

与此相关的特定于glibc的函数(应该在大多数Linux环境中都可以找到)是random(),或者您可能对其线程安全版本random_r()感兴趣。在将结构体random_data传递给random_r()之前,必须使用initstate_r()初始化它。

下面是一个快速的代码示例:

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

void xxx (void) {
    unsigned int seed = (unsigned int) time(NULL);
    char rnd_state[17] = {0};
    struct random_data rnd_st_buf = {0};
    initstate_r(seed, &rnd_state[0], 17, &rnd_st_buf);
    for(size_t idx = 0; idx < 8; idx++) {
        int32_t rnd_int = 0;
        char rnd_seq_str[6] = {0};
        random_r(&rnd_st_buf, &rnd_int);
        memcpy((char *)&rnd_seq_str[0], (char *)&rnd_int, 4);
        printf("random number : 0x%08x,  \n", rnd_int);
    }
}
#include <stdio.h>
#include <dos.h>

int random(int range);

int main(void)
{
    printf("%d", random(10));
    return 0;
}

int random(int range)
{
    struct time t;
    int r;

    gettime(&t);
    r = t.ti_sec % range;
    return r;
}

我们来看看这个。首先,我们使用srand()函数来为随机化器播种。基本上,计算机可以根据输入给srand()的数字生成随机数。如果你给出相同的种子值,那么每次都会生成相同的随机数。

因此,我们必须用一个总是在变化的值来给随机化器播种。我们通过time()函数将当前时间的值提供给它来实现这一点。

现在,当我们调用rand()时,每次都会产生一个新的随机数。

    #include <stdio.h>

    int random_number(int min_num, int max_num);

    int main(void)
    {
        printf("Min : 1 Max : 40 %d\n", random_number(1,40));
        printf("Min : 100 Max : 1000 %d\n",random_number(100,1000));
        return 0;
    }

    int random_number(int min_num, int max_num)
    {
        int result = 0, low_num = 0, hi_num = 0;

        if (min_num < max_num)
        {
            low_num = min_num;
            hi_num = max_num + 1; // include max_num in output
        } else {
            low_num = max_num + 1; // include max_num in output
            hi_num = min_num;
        }

        srand(time(NULL));
        result = (rand() % (hi_num - low_num)) + low_num;
        return result;
    }

您希望使用rand()。注意(非常重要):确保为rand函数设置了种子。如果你不这样做,你的随机数就不是真正的随机。这是非常、非常、非常重要的。值得庆幸的是,您通常可以使用系统滴答计时器和日期的某种组合来获得良好的种子。