Table of Content


这篇博客主要介绍 C 语言的 rand()srand() 以及 time() 函数。

rand()

rand() 函数是一个定义在 stdlib.h 中的函数,可以用来获得随机数把标准函数调用语句直接当数字使用就可以得到随机数。

int rand(void);
// 取一个 a 到 b 之间的随机数:
a + rand() % (b - a);

srand()

srand() 函数是一个定义在 stdlib.h 中的函数,可以置新的随机数种子,srand标准函数在每个程序中只应该使用一次。

void srand(unsigned int seed);

time()

time() 函数是一个定义在 time.h 中的函数,可以获得当前的系统时间,直接将time标准函数调用语句当作数字使用就可以得到代表时间的整数。

在 C 语言中时间有两种记录方式:

  • time_t 整数方式,返回时间和 1970 年 1 月 1 日 0 时 0 分 0 秒之间的秒差。

  • struct tm 结构方式,采用 xxxx 年 xx 月 xx 日 xx 时 xx 分 xx 秒形式,结构中包含代表年、月、日、时、分、秒、星期、年日的成员。

struct tm {
	int tm_sec;         /* seconds */
	int tm_min;         /* minutes */
	int tm_hour;        /* hours */
	int tm_mday;        /* day of the month */
	int tm_mon;         /* month */
	int tm_year;        /* year */
	int tm_wday;        /* day of the week */
	int tm_yday;        /* day in the year */
	int tm_isdst;       /* daylight saving time */
};

C 语言提供了 time_t 转换函数:

  • ctime()time_t 整数方式转换为字符串,显示为年月日方式(美式),定义在 time.h 中。
char *ctime(const time_t *timep);
char *ctime_r(const time_t *timep, char *buf);
  • localtime()time_t 整数方式转换为 struct tm 结构方式,程序员可以自由定义显示方式,定义在 time.h 中。
struct tm *localtime(const time_t *timep);
struct tm *localtime_r(const time_t *timep, struct tm *result);
  • 其他time函数:
Defined in <time.h>
char *asctime(const struct tm *tm);
char *asctime_r(const struct tm *tm, char *buf);
struct tm *gmtime(const time_t *timep);
struct tm *gmtime_r(const time_t *timep, struct tm *result);
time_t mktime(struct tm *tm);
/*
    rand、srand、time练习
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    srand(time(0));
    printf("%d\n",rand());
    printf("%d\n",rand());
    printf("%d\n",rand());
    return 0;
}