且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 C 中生成随机整数?

更新时间:2023-02-10 14:18:37

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.

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