用C++编写一个年历显示(尽可能简单)功能要求,(1)输入一个年份,在屏幕上显示该年的日历,假定输入的年份,在1940到2040年之间,(2)输年月,输出该月的日历(3)输入年月日,输出该天是星期几
时间: 2023-06-14 18:03:20 浏览: 108
以下是一个简单的C语言程序,实现了年历显示的功能,包括输入年份,输出整年日历,输入年月,输出该月日历,输入年月日,输出该天星期几。代码中使用了time.h头文件中的一些函数,如mktime()、localtime()等,需要在编译时加上-lm参数链接数学库。
```c
#include <stdio.h>
#include <time.h>
#include <math.h>
int is_leap_year(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int days_in_month(int year, int month) {
if (month == 2) {
return is_leap_year(year) ? 29 : 28;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
} else {
return 31;
}
}
int days_in_year(int year) {
return is_leap_year(year) ? 366 : 365;
}
int week_day(int year, int month, int day) {
struct tm tm = { 0 };
tm.tm_year = year - 1900;
tm.tm_mon = month - 1;
tm.tm_mday = day;
time_t t = mktime(&tm);
struct tm *tt = localtime(&t);
return tt->tm_wday;
}
void print_calendar(int year) {
printf("%d\n", year);
int first_day = week_day(year, 1, 1);
int days = days_in_year(year);
int month = 1, day = 1;
for (int i = 0; i < 7; i++) {
if (i < first_day) {
printf(" ");
} else {
printf("%4d", day);
day++;
}
}
printf("\n");
for (int i = 0; i < days - 7 + first_day; i++) {
if (i % 7 == 0) {
printf("\n");
}
printf("%4d", day);
day++;
}
printf("\n");
}
void print_month(int year, int month) {
printf("%d-%d\n", year, month);
int first_day = week_day(year, month, 1);
int days = days_in_month(year, month);
int day = 1;
for (int i = 0; i < 7; i++) {
if (i < first_day) {
printf(" ");
} else {
printf("%2d ", day);
day++;
}
}
printf("\n");
for (int i = 0; i < days - 7 + first_day; i++) {
if (i % 7 == 0) {
printf("\n");
}
printf("%2d ", day);
day++;
}
printf("\n");
}
void print_weekday(int year, int month, int day) {
char *weekday[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
int w = week_day(year, month, day);
printf("%s\n", weekday[w]);
}
int main() {
int year, month, day;
printf("Enter year: ");
scanf("%d", &year);
if (year < 1940 || year > 2040) {
printf("Invalid year!\n");
return 0;
}
printf("Enter month (0 for whole year): ");
scanf("%d", &month);
if (month == 0) {
print_calendar(year);
} else if (month >= 1 && month <= 12) {
print_month(year, month);
} else {
printf("Invalid month!\n");
return 0;
}
if (month == 0) {
printf("Enter date (dd): ");
scanf("%d", &day);
if (day < 1 || day > 31) {
printf("Invalid date!\n");
return 0;
}
print_weekday(year, 1, day);
} else {
printf("Enter date (dd): ");
scanf("%d", &day);
if (day < 1 || day > days_in_month(year, month)) {
printf("Invalid date!\n");
return 0;
}
print_weekday(year, month, day);
}
return 0;
}
```
在控制台上运行程序,输入年份、月份和日期,即可输出相应的日历和星期几。例如,输入2022、10、15,即可输出2022年10月的日历和15日是星期六。
阅读全文