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


当前回答

你可以生成随机字符,然后将它们视为int:

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

typedef double rand_type; // change double to int

rand_type my_rand() {
    char buff[sizeof(rand_type)];
    for (size_t i = 0 ; i < sizeof(rand_type) ; ++i)
        buff[i] = (char) rand();
    return *(rand_type *) buff;
}

int main() {
    int i ; // srand as you want
    for (i = 0 ; i < 10 ; ++i)
        printf("%g\n", my_rand()); // change %g to %d
    return 0 ;
}

其他回答

希望这比仅仅使用srand(time(NULL))更随机。

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

int main(int argc, char **argv)
{
    srand((unsigned int)**main + (unsigned int)&argc + (unsigned int)time(NULL));
    srand(rand());

    for (int i = 0; i < 10; i++)
        printf("%d\n", rand());
}
#include <stdio.h>
#include <stdlib.h>

void main() 
{
    int visited[100];
    int randValue, a, b, vindex = 0;

    randValue = (rand() % 100) + 1;

    while (vindex < 100) {
        for (b = 0; b < vindex; b++) {
            if (visited[b] == randValue) {
                randValue = (rand() % 100) + 1;
                b = 0;
            }
        }

        visited[vindex++] = randValue;
    }

    for (a = 0; a < 100; a++)
        printf("%d ", visited[a]);
}

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)

如果你需要安全的随机字符或整数:

正如在如何在各种编程语言中安全地生成随机数中提到的,你会想要做以下事情之一:

使用libsodium的randombytes API 重新实现你自己需要的libsodium的sysrandom实现,非常小心 更广泛地说,使用/dev/urandom,而不是/dev/random。而不是OpenSSL(或其他用户空间prng)。

例如:

#include "sodium.h"

int foo()
{
    char myString[32];
    uint32_t myInt;

    if (sodium_init() < 0) {
        /* panic! the library couldn't be initialized, it is not safe to use */
        return 1; 
    }


    /* myString will be an array of 32 random bytes, not null-terminated */        
    randombytes_buf(myString, 32);

    /* myInt will be a random number between 0 and 9 */
    myInt = randombytes_uniform(10);
}

Randombytes_uniform()是加密安全且无偏倚的。

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

int rand(void);

void srand(unsigned seed);

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

long random(void);

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