C语言实现一个给定范围的随机数获取
- 使用宏函数直接实现,方便简单,使用前设置种子,避免每次随机结果相同
上代码
#include <windows.h>
#include <stdlib.h> // rand(), srand()
#include <stdio.h>
#define GetRandom( min, max ) ((rand() % (int)(((max) + 1) - (min))) + (min))
int main(int argc, char** argv)
{
/* srand() 设置种子 */
srand(GetTickCount()); // 也可以使用time()函数得到时间做种子
int nRandNum = GetRandom(10,20);
printf("%d",nRandNum);
return 0;
}