写一个时间函数 这个函数被主函数调用后显示时间
时间: 2024-03-22 15:41:21 浏览: 24
好的,可以使用 C 语言中的 time.h 头文件中的函数来获取当前时间,并使用 printf 函数将其输出。下面是一个简单的示例:
```c
#include <stdio.h>
#include <time.h>
void display_time() {
time_t current_time;
struct tm * time_info;
char time_string[9];
time(¤t_time);
time_info = localtime(¤t_time);
strftime(time_string, sizeof(time_string), "%H:%M:%S", time_info);
printf("The current time is %s\n", time_string);
}
int main() {
display_time();
return 0;
}
```
这个函数被调用后,会输出当前的时间,格式为 "HH:MM:SS"。你可以根据需要修改输出的格式。
相关问题
写一个带有时间返回值的函数,这个函数能被主函数调用
好的,下面是一个示例函数,它返回当前时间的整数表示(自 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 函数将返回的时间值输出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)