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


当前回答

C程序生成9到50之间的随机数

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

int main()
{
    srand(time(NULL));
    int lowerLimit = 10, upperLimit = 50;
    int r =  lowerLimit + rand() % (upperLimit - lowerLimit);
    printf("%d", r);
}

通常我们可以生成一个介于lowerLimit和upperLimit-1之间的随机数

例如,lowerLimit包含或说r∈[lowerLimit, upperLimit)

其他回答

如果您需要比stdlib提供的质量更好的伪随机数,请检查Mersenne Twister。它也更快。示例实现有很多,例如这里。

注意:为了安全性,不要使用rand()。如果您需要加密安全的号码,请参阅此答案。

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

srand(time(NULL));   // Initialization, should only be called once.
int r = rand();      // Returns a pseudo-random integer between 0 and RAND_MAX.

在Linux上,您可能更喜欢使用random和srandom。

如果您需要128个安全随机位,符合RFC 1750的解决方案是读取已知可以生成可用熵位的硬件源(例如旋转磁盘)。更好的是,好的实现应该使用混合函数组合多个源,并最终通过重新映射或删除输出来消除输出分布的倾斜。

如果你需要更多的比特,你需要做的就是从128个安全随机比特的序列开始,并将其拉伸到所需的长度,将其映射到人类可读的文本等等。

如果你想在C中生成一个安全的随机数,我将遵循这里的源代码:

https://wiki.sei.cmu.edu/confluence/display/c/MSC30-C.+Do+not+use+the+rand%28%29+function+for+generating+pseudorandom+numbers

注意,对于Windows bbcryptgenrandom是使用的,而不是CryptGenRandom,在过去的20年里已经变得不安全。您可以亲自确认BCryptGenRandom符合RFC 1750。

For POSIX-compliant operating systems, e.g. Ubuntu (a flavor of Linux), you can simply read from /dev/urandom or /dev/random, which is a file-like interface to a device that generates bits of entropy by combining multiple sources in an RFC 1750 compliant fashion. You can read a desired number of bytes from these "files" with read or fread just like you would any other file, but note that reads from /dev/random will block until a enough new bits of entropy are available, whereas /dev/urandom will not, which can be a security issue. You can get around that by checking the size of the available entropy pool, either my reading from entropy_avail, or by using ioctl.

<stdlib.h>中的rand()函数返回一个介于0和RAND_MAX之间的伪随机整数。你可以使用srand(unsigned int seed)来设置种子。

通常的做法是将%操作符与rand()结合使用以获得不同的范围(但请记住,这在一定程度上破坏了一致性)。例如:

/* random int between 0 and 19 */
int r = rand() % 20;

如果你真的在乎一致性,你可以这样做:

/* Returns an integer in the range [0, n).
 *
 * Uses rand(), and so is affected-by/affects the same seed.
 */
int randint(int n) {
  if ((n - 1) == RAND_MAX) {
    return rand();
  } else {
    // Supporting larger values for n would requires an even more
    // elaborate implementation that combines multiple calls to rand()
    assert (n <= RAND_MAX)

    // Chop off all of the values that would cause skew...
    int end = RAND_MAX / n; // truncate skew
    assert (end > 0);
    end *= n;

    // ... and ignore results from rand() that fall above that limit.
    // (Worst case the loop condition should succeed 50% of the time,
    // so we can expect to bail out of this loop pretty quickly.)
    int r;
    while ((r = rand()) >= end);

    return r % n;
  }
}

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

int rand(void);

void srand(unsigned seed);

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

long random(void);

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