# 标准库stdlib.h函数rand() **原型** ```c int rand(void); ``` **说明** 该函数会产生一个介于 0 和 RAND_MAX 之间的随机数,RAND_MAX 是 stdlib.h 库中定义的一预定义宏,一般会定义为32767(2^15^-1)。使用 rand 在确定的范围内生成平凡伪随机数的典型方法是使用返回值与范围跨度的模并添加范围的初始值。 **使用** ```c int v1 = rand() % 100; //v1 in the range 0 to 99 int v2 = rand() % 100 + 1; //v1 in the range 0 to 100 int v3 = rand() % 30 + 1985; //v3 in the range 1985-2014 ``` **实例** ```c #include /* printf, scanf, puts, NULL */ #include /* srand, rand */ #include /* time */ int main () { int iSecret, iGuess; /* initialize random seed: */ srand (time(NULL)); /* generate secret number between 1 and 10: */ iSecret = rand() % 10 + 1; do { printf ("Guess the number (1 to 10): "); scanf ("%d",&iGuess); if (iSecretiGuess) puts ("The secret number is higher"); } while (iSecret!=iGuess); puts ("Congratulations!"); return 0; } ```