rand() 函数在 stdlib.h 头文件中定义。此函数用于生成 0 到 RAND_MAX 范围内的伪随机数 (PRNG)。RAND_MAX 是一个符号常量,根据 C 库的不同,其值大于但不小于 32767。
int rand(void);
rand() 函数不接受任何参数。
rand() 函数返回一个介于 0 和 RAND_MAX 之间的整数值。
| 输入 | 返回值 |
|---|---|
| 成功 | 整数值 (0- RAND_MAX) |
#include <stdio.h>
#include <stdlib.h>
int main()
{
int k, num;
time_t tm;
num = 5;
/* Intializes random number*/
srand((unsigned) time(&tm;));
/* random numbers from 0 to 49 */
for( k = 0 ; k < num ; k++ ) {
printf("%d\n", rand() % 50);
}
return(0);
}
输出
38 45 29 29 47
#include <stdio.h>
#include <stdlib.h>
int main (){
printf (" Random number is: %d", rand());
printf ("\nRandom number is: %d", rand());
printf (" \n Random number is: %d", rand());
printf ("\n Random number is: %d", rand());
getch();
}
输出
Random number is: 41 Random number is: 18467 Random number is: 6334 Random number is: 26500