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


当前回答

在现代的x86_64 cpu上,您可以通过_rdrand64_step()使用硬件随机数生成器。

示例代码:

#include <immintrin.h>

uint64_t randVal;
if(!_rdrand64_step(&randVal)) {
  // Report an error here: random number generation has failed!
}
// If no error occured, randVal contains a random 64-bit number

其他回答

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

下面是我的方法(围绕rand()的包装器):

我还扩展到允许min为INT_MIN而max为INT_MAX的情况,这通常不可能单独使用rand(),因为它返回从0到RAND_MAX的值,包括(1/2范围)。

像这样使用它:

const int MIN = 1;
const int MAX = 1024;
// Get a pseudo-random number between MIN and MAX, **inclusive**.
// Seeding of the pseudo-random number generator automatically occurs
// the very first time you call it.
int random_num = utils_rand(MIN, MAX);

定义和氧描述:

#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>

/// \brief      Use linear interpolation to rescale, or "map" value `val` from range
///             `in_min` to `in_max`, inclusive, to range `out_min` to `out_max`, inclusive.
/// \details    Similar to Arduino's ingenious `map()` function:
///             https://www.arduino.cc/reference/en/language/functions/math/map/
///
/// TODO(gabriel): turn this into a gcc statement expression instead to prevent the potential for
/// the "double evaluation" bug. See `MIN()` and `MAX()` above.
#define UTILS_MAP(val, in_min, in_max, out_min, out_max) \
    (((val) - (in_min)) * ((out_max) - (out_min)) / ((in_max) - (in_min)) + (out_min))

/// \brief      Obtain a pseudo-random integer value between `min` and `max`, **inclusive**.
/// \details    1. If `(max - min + 1) > RAND_MAX`, then the range of values returned will be
///             **scaled** to the range `max - min + 1`, and centered over the center of the
///             range at `(min + max)/2`. Scaling the numbers means that in the case of scaling,
///             not all numbers can even be reached. However, you will still be assured to have
///             a random distribution of numbers across the full range.
///             2. Also, the first time per program run that you call this function, it will
///             automatically seed the pseudo-random number generator with your system's
///             current time in seconds.
/// \param[in]  min         The minimum pseudo-random number you'd like, inclusive. Can be positive
///                         OR negative.
/// \param[in]  max         The maximum pseudo-random number you'd like, inclusive. Can be positive
///                         OR negative.
/// \return     A pseudo-random integer value between `min` and `max`, **inclusive**.
int utils_rand(int min, int max)
{
    static bool first_run = true;
    if (first_run)
    {
        // seed the pseudo-random number generator with the seconds time the very first run
        time_t time_now_sec = time(NULL);
        srand(time_now_sec);
        first_run = false;
    }

    int range = max - min + 1;
    int random_num = rand();  // random num from 0 to RAND_MAX, inclusive

    if (range > RAND_MAX)
    {
        static_assert(
            sizeof(long int) > sizeof(int),
            "This must be true or else the below mapping/scaling may have undefined overflow "
            "and not work properly. In such a case, try casting to `long long int` instead of "
            "just `long int`, and update this static_assert accordingly.");

        random_num = UTILS_MAP((long int)random_num, (long int)0, (long int)RAND_MAX, (long int)min,
                               (long int)max);
        return random_num;
    }

    // This is presumably a faster approach than the map/scaling function above, so do this faster
    // approach below whenever you don't **have** to do the more-complicated approach above.
    random_num %= range;
    random_num += min;

    return random_num;
}

参见:

[我在写下上面的答案后发现了这个问答,但它显然非常相关,他们对非缩放范围的情况做了同样的事情]我如何从rand()中获得特定的数字范围? [我需要进一步研究和阅读这个答案-似乎有一些好的观点,保持良好的随机性不使用模量]我如何从rand()得到一个特定的数字范围? http://c-faq.com/lib/randrange.html

STL是c++,不是C,所以我不知道你想要什么。然而,如果你想使用C语言,则有rand()和srand()函数:

int rand(void);

void srand(unsigned seed);

它们都是ANSI c的一部分。还有random()函数:

long random(void);

但据我所知,random()不是标准的ANSI c。第三方库可能不是一个坏主意,但这完全取决于您真正需要生成的数字的随机程度。

标准的C函数是rand()。它可以用来发纸牌,但很糟糕。rand()的许多实现通过一个简短的数字列表循环,低位的周期更短。一些程序调用rand()的方式很糟糕,计算一个传递给srand()的好种子也很困难。

在C语言中生成随机数的最佳方法是使用第三方库,如OpenSSL。例如,

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <openssl/rand.h>

/* Random integer in [0, limit) */
unsigned int random_uint(unsigned int limit) {
    union {
        unsigned int i;
        unsigned char c[sizeof(unsigned int)];
    } u;

    do {
        if (!RAND_bytes(u.c, sizeof(u.c))) {
            fprintf(stderr, "Can't get random bytes!\n");
            exit(1);
        }
    } while (u.i < (-limit % limit)); /* u.i < (2**size % limit) */
    return u.i % limit;
}

/* Random double in [0.0, 1.0) */
double random_double() {
    union {
        uint64_t i;
        unsigned char c[sizeof(uint64_t)];
    } u;

    if (!RAND_bytes(u.c, sizeof(u.c))) {
        fprintf(stderr, "Can't get random bytes!\n");
        exit(1);
    }
    /* 53 bits / 2**53 */
    return (u.i >> 11) * (1.0/9007199254740992.0);
}

int main() {
    printf("Dice: %d\n", (int)(random_uint(6) + 1));
    printf("Double: %f\n", random_double());
    return 0;
}

为什么有这么多代码?其他语言,如Java和Ruby,都有用于随机整数或浮点数的函数。OpenSSL只提供随机字节,因此我尝试模拟Java或Ruby如何将它们转换为整数或浮点数。

对于整数,我们要避免模偏置。假设我们从rand() % 10000中得到一些随机的4位整数,但是rand()只能返回0到32767(就像在Microsoft Windows中那样)。0到2767之间的每个数字出现的频率要高于2768到9999之间的每个数字。为了消除偏差,我们可以在值低于2768时重试rand(),因为从2768到32767的30000值统一映射到从0到9999的10000值。

对于浮点数,我们需要53个随机位,因为double类型拥有53位精度(假设它是IEEE double类型)。如果我们使用超过53位,就会产生舍入偏差。有些程序员写rand() / (double)RAND_MAX这样的代码,但是rand()可能只返回31位,或者在Windows中只返回15位。

OpenSSL的RAND_bytes()可能通过读取Linux中的/dev/urandom来自行播种。如果我们需要很多随机数,从/dev/urandom读取它们会很慢,因为它们必须从内核复制。允许OpenSSL从种子中生成更多的随机数会更快。

更多关于随机数的内容:

Perl的Perl_seed()是一个如何在C中为srand()计算种子的例子。如果它不能读取/dev/ urrandom,它会混合来自当前时间、进程ID和一些指针的比特。 OpenBSD的arc4random_uniform()解释了模偏置。 random的Java API描述了从随机整数中去除偏差的算法,并将53位打包到随机浮点数中。

#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;
}