#include <time.h>
time_t time(time_t *tloc);
功能:获取当前系统时间,它会返回自1970年1月1日 00:00:00 到现在一共过多少秒(格林时间)。
int rand(void);
功能:返回一个随机整数
void srand(unsigned int seed);
功能:设置随机数的种子
int abs(int j);
功能:求绝对值
double sqrt(double x);
功能:对x进行开方
double pow(double x, double y);
功能:计算x的y次方
注意:使用pow、sqrt这种数学函数是,需要额外链接数学库,gcc xxx.c -lm
int system(const char *command);
功能:调用系统命令
练习1:随机产生10个[10,99]的整数,按照升序输出。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc,const char* argv[])
{
srand(time(NULL));
int arr[10];
for(int i=0,j; i<10; i++)
{
int num = rand() % 90 + 10;
for(j=i; j>0 && num < arr[j-1]; j--)
{
arr[j] = arr[j-1];
}
arr[j] = num;
}
for(int i=0; i<10; i++)
{
printf("%d ",arr[i]);
}
return 0;
}
练习2:随机生成一注双色球彩票号,红球一共6组,每组从1-33中抽取一个,六个互相不重复。然后蓝球是从1-16中抽取一个数字,这整个组成的双色球彩票。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc,const char* argv[])
{
char red[6] = {} , cnt = 0 , i;
srand(time(NULL));
printf("red:");
while(cnt < 6)
{
// 随机生成一个[1,33]之间的整数
int num = rand() % 33 + 1;
// 查询num是否重复
for(i=0; i<cnt; i++)
{
// 如果num在数组出现过则循环提前结束
if(num == red[i])
break;
}
// for循环没有提前结束,num未出现过
if(i == cnt)
{
red[cnt++] = num;
printf("%d ",num);
}
}
printf("blue:%d\n",rand()%16+1);
return 0;
}