Skip to content

Instantly share code, notes, and snippets.

@hackerain
Created May 5, 2013 09:54
Show Gist options
  • Save hackerain/5520350 to your computer and use it in GitHub Desktop.
Save hackerain/5520350 to your computer and use it in GitHub Desktop.
C语言产生随机数
C语言产生随机数需要调用stdlib.h头文件中的两个函数:
int rand(void): 产生一个0到RAND_MAX之间的随机整数。(RAND_MAX定义在stdlib.h, 其值为2147483647)
void srand(int seed): 用于初始化种子,便于每次产生不同的随机数。
/*
如果要产生其他范围内的整数,可以使用取余运算实现。以下代码为产生0~100之间的随机数:
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[])
{
int i;
srand((int)time(0));
for (i=0; i<10; i++) {
printf("%d\n", rand()%100);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment