【C语言笔记】关于随机数的总结
C语言的库头文件stdlib.h中有个生成随机数的函数:
int rand(void);
该函数返回0~RAND_MAX之间的随机数,在stdlib.h中可知道,RAND_MAX为0x7FFF,如:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("%d\n",rand());
return 0;
}
void srand(unsigned int seed);
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(1);
printf("%d\n",rand());
srand(2);
printf("%d\n",rand());
srand(3);
printf("%d\n",rand());
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(520);
printf("%d\n",rand());
srand(520);
printf("%d\n",rand());
srand(520);
printf("%d\n",rand());
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int loop;
srand((unsigned)time(NULL));
for (loop = 0; loop < 10; loop++)
{
printf("%d\n",rand()%10);
}
return 0;
}
常用关键字列表
赞 (0)