C语言编写一个函数,接受用户输入的年份、月份和日期作为参数,然后计算并返回该日期对应的星期几。
时间: 2024-11-03 16:22:09 浏览: 45
在C语言中,我们可以使用`mktime()`函数和`strftime()`函数来计算和获取特定日期的星期几。首先,你需要包含头文件`<stdio.h>`和`<time.h>`。下面是一个简单的示例函数,它接受年份、月份和日期作为参数,并返回相应的英文星期几名称:
```c
#include <stdio.h>
#include <time.h>
// 函数声明
char* get_weekday(int year, int month, int day);
// 主要的函数实现
char* get_weekday(int year, int month, int day) {
struct tm time_info = {0};
time_info.tm_year = year - 1900; // 转换为自从1900年以来的年份
time_info.tm_mon = month - 1; // 月份从0开始计数
time_info.tm_mday = day;
// 计算时间戳
time_t timestamp = mktime(&time_info);
// 格式化时间为英文星期几
char week_day[10];
strftime(week_day, sizeof(week_day), "%A", localtime(×tamp));
return week_day;
}
int main() {
int year, month, day;
printf("请输入年月日(格式:YYYY MM DD): ");
scanf("%d %d %d", &year, &month, &day);
char* weekday = get_weekday(year, month, day);
printf("日期 %d-%02d-%02d是星期% s\n", year, month, day, weekday);
return 0;
}
```
当你运行这个程序时,它会提示用户输入年月日,然后显示对应日期的星期几。
阅读全文
相关推荐



















