如何返回一个介于[2020/1/1,00:00:00-2020/12/31,23:59:59]之间的随机时间
本帖最后由 eobeom 于 2020-11-18 12:42 编辑#include <stdio.h>
#include <stdlib.h>
#include <time.h>
time_t xtime(int time_index);
void print_local_time(time_t t) {
\\补全函数
return;
}
int main(void) {
time_t t;
int tindex;
srand(0);
scanf("%d", &tindex);
t = xtime(tindex);
print_local_time(t);
return 0;
}
最后输出的格式是yy/mm/dd,xx:xx:xx, 星期
请问这个程序需要如何补全 #include <stdio.h>
#include <stdlib.h>
#include <time.h>
time_t xtime(int time_index)
{
time_t temp;
struct tm t = {0};
time(&temp);
t = *localtime(&temp);
//返回2020-01-01 00:00:00的时间戳
if(time_index == 0)
{
t.tm_mon = 1;
t.tm_mday = 1;
t.tm_hour = 0;
t.tm_min = 0;
t.tm_sec = 0;
}
//返回2020-12-31 23:59:59的时间戳
else
{
t.tm_mon = 11;
t.tm_mday = 31;
t.tm_hour = 23;
t.tm_min = 59;
t.tm_sec = 59;
}
return mktime(&t);
}
void print_local_time(time_t t)
{
struct tm ts = *localtime(&t);
printf("%4d-%02d-%02d,%02d:%02d:%02d,weekday %d\n",
ts.tm_year + 1900 ,
ts.tm_mon+1,
ts.tm_mday,
ts.tm_hour,
ts.tm_min,
ts.tm_sec,
ts.tm_wday);
return;
}
int main(void)
{
time_t begin,end;
time_t trand;
int i = 0;
srand(time(NULL));
begin = xtime(0);
end = xtime(1);
//生成100个随机时间
while(i++ < 100)
{
//由于rand()生成的随机数可能会比较小,取rand()*rand()将之放大
trand = begin + (rand() * rand() % (end - begin));
print_local_time(trand);
}
return 0;
}
页:
[1]