How to generate a random int in C?

2018-12-31 05:23发布

Is there a function to generate a random int number in C? Or will I have to use a third party library?

标签: c random
24条回答
妖精总统
2楼-- · 2018-12-31 05:54

Despite all the people suggestion rand() here, you don't want to use rand() unless you have to! The random numbers that rand() produces are often very bad. To quote from the Linux man page:

The versions of rand() and srand() in the Linux C Library use the same random number generator as random(3) and srandom(3), so the lower-order bits should be as random as the higher-order bits. However, on older rand() implementations, and on current implementations on different systems, the lower-order bits are much less random than the higher-order bits. Do not use this function in applications intended to be portable when good randomness is needed. (Use random(3) instead.)

Regarding portability, random() is also defined by the POSIX standard for quite some time now. rand() is older, it appeared already in the first POSIX.1 spec (IEEE Std 1003.1-1988), whereas random() first appeared in POSIX.1-2001 (IEEE Std 1003.1-2001), yet the current POSIX standard is already POSIX.1-2008 (IEEE Std 1003.1-2008), which received an update just a year ago (IEEE Std 1003.1-2008, 2016 Edition). So I would consider random() to be very portable.

POSIX.1-2001 also introduced the lrand48() and mrand48() functions, see here:

This family of functions shall generate pseudo-random numbers using a linear congruential algorithm and 48-bit integer arithmetic.

And pretty good pseudo random source is the arc4random() function that is available on many systems. Not part of any official standard, appeared in BSD around 1997 but you can find it on systems like Linux and macOS/iOS.

查看更多
看淡一切
3楼-- · 2018-12-31 05:57

My minimalistic solution should work for random numbers in range [min, max). Use srand(time(NULL)) before invoking the function.

int range_rand(int min_num, int max_num) {
    if (min_num >= max_num) {
        fprintf(stderr, "min_num is greater or equal than max_num!\n"); 
    }
    return min_num + (rand() % (max_num - min_num));
} 
查看更多
宁负流年不负卿
4楼-- · 2018-12-31 05:59

If you need secure random characters or integers:

As addressed in how to safely generate random numbers in various programming languages, you'll want to do one of the following:

For example:

#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() is cryptographically secure and unbiased.

查看更多
裙下三千臣
5楼-- · 2018-12-31 06:00

Note: Don't use rand() for security. If you need a cryptographically secure number, see this answer instead.

#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.

Edit: On Linux, you might prefer to use random and srandom.

查看更多
忆尘夕之涩
6楼-- · 2018-12-31 06:00

Try this, I put it together from some of the concepts already referenced above:

/*    
Uses the srand() function to seed the random number generator based on time value,
then returns an integer in the range 1 to max. Call this with random(n) where n is an integer, and you get an integer as a return value.
 */

int random(int max) {
    srand((unsigned) time(NULL));
    return (rand() % max) + 1;
}
查看更多
旧时光的记忆
7楼-- · 2018-12-31 06:04
#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]);
}
查看更多
登录 后发表回答