写一个带有时间返回值的函数,这个函数能被主函数调用
时间: 2024-03-22 15:41:22 浏览: 23
好的,下面是一个示例函数,它返回当前时间的整数表示(自 1970 年 1 月 1 日 0 点以来的秒数):
```c
#include <stdio.h>
#include <time.h>
time_t get_current_time() {
time_t current_time;
time(¤t_time);
return current_time;
}
int main() {
time_t current_time = get_current_time();
printf("The current time is %ld\n", current_time);
return 0;
}
```
这个函数将返回一个 time_t 类型的整数值,表示当前时间。在主函数中调用该函数,并将返回值存储在一个变量中,然后使用 printf 函数将其输出。
相关问题
写一个带有时间返回值的函数,这个函数能被主函数调用,时间是时分秒
好的,下面是一个示例函数,它返回当前时间的时、分、秒:
```c
#include <stdio.h>
#include <time.h>
void get_current_time(int *hour, int *minute, int *second) {
time_t current_time;
struct tm * time_info;
time(¤t_time);
time_info = localtime(¤t_time);
*hour = time_info->tm_hour;
*minute = time_info->tm_min;
*second = time_info->tm_sec;
}
int main() {
int hour, minute, second;
get_current_time(&hour, &minute, &second);
printf("The current time is %02d:%02d:%02d\n", hour, minute, second);
return 0;
}
```
在这个示例中,我们定义了一个名为 `get_current_time` 的函数,它接收三个整型指针作为参数,用于返回当前时间的小时数、分钟数和秒数。我们使用 `localtime` 函数获取当前时间,并将其存储在 `struct tm` 类型的变量中。然后,我们将时、分、秒分别存储在传入的指针变量中。最后,在主函数中调用该函数,并使用 printf 函数将返回的时间值输出。
写一个时间函数,这个函数 有return 返回值 返回的是时分秒,主函数调用时间函数显示时间
好的,下面是一个示例函数,它返回当前时间的时、分、秒:
```c
#include <stdio.h>
#include <time.h>
char* get_current_time() {
time_t current_time;
struct tm * time_info;
static char time_string[9];
time(¤t_time);
time_info = localtime(¤t_time);
strftime(time_string, sizeof(time_string), "%H:%M:%S", time_info);
return time_string;
}
int main() {
char *time_str = get_current_time();
printf("The current time is %s\n", time_str);
return 0;
}
```
在这个示例中,我们定义了一个名为 `get_current_time` 的函数,它返回当前时间的时、分、秒。我们使用 `localtime` 函数获取当前时间,并将其存储在 `struct tm` 类型的变量中。然后,我们使用 `strftime` 函数将时间格式化为字符串,并将其存储在静态的字符数组中。最后,我们返回这个字符串指针。
在主函数中,我们调用 `get_current_time` 函数,将返回的字符串指针存储在一个变量中。然后,我们使用 printf 函数将返回的时间值输出。