编写下列函数,假定time结构包含三个成员:hours、minutes和seconds(都是 int 类型)。\nstruct time split_time(long total_seconds);\ntotal_seconds是从午夜开始的秒数。函数返回一个包含等价时间的结构,等价的时间用小时\n(023)、分钟(059)和秒(0~59)表示。
一种写法:
#include <stdio.h>
#include <stdlib.h>
struct Time{
int hours;
int minutes;
int seconds;
};
struct Time* split_time(long total_seconds)
{
struct Time *t = (struct Time*)malloc(sizeof(struct Time));
t->hours = total_seconds / 3600;
total_seconds %= 3600;
t->minutes = total_seconds / 60;
total_seconds %= 60;
t->seconds = total_seconds;
return t;
}
另一种写法:
#include <stdio.h>
#include <stdlib.h>
struct Time{
int hours;
int minutes;
int seconds;
}t = {0,0,0};
struct Time split_time(long total_seconds)
{
t.hours = total_seconds / 3600;
total_seconds %= 3600;
t.minutes = total_seconds / 60;
total_seconds %= 60;
t.seconds = total_seconds;
return t;
}
两个函数调用,供参考:
#include <stdio.h>
#include <stdlib.h>
struct Time{
int hours;
int minutes;
int seconds;
}t = {0,0,0};
struct Time split_time(long total_seconds)
{
t.hours = total_seconds / 3600;
total_seconds %= 3600;
t.minutes = total_seconds / 60;
total_seconds %= 60;
t.seconds = total_seconds;
return t;
}
struct Time* split_time1(long total_seconds)
{
struct Time *t = (struct Time*)malloc(sizeof(struct Time));
t->hours = total_seconds / 3600;
total_seconds %= 3600;
t->minutes = total_seconds / 60;
total_seconds %= 60;
t->seconds = total_seconds;
return t;
}
int main()
{
struct Time start, *p_start;
start = split_time(156800); // 方式一
printf("%d:%d:%d\n",start.hours, start.minutes, start.seconds);
printf("%d:%d:%d\n",t.hours, t.minutes, t.seconds);//因为 t 是全局变量,直接用 t 输出也可以
p_start = split_time1(246800); // 方式二
printf("%d:%d:%d\n",p_start->hours, p_start->minutes, p_start->seconds);
return 0;
}