c语言给出月的天数和这个月开始的第一天属于星期几打印出月历
时间: 2024-05-01 19:21:44 浏览: 20
好的,我可以帮你解决这个问题。以下是一个简单的 C 代码示例,可以根据给定的月份和年份来打印出该月份的日历。
```c
#include <stdio.h>
int main() {
int year, month, day, week_day;
int days_in_month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
printf("Enter year: ");
scanf("%d", &year);
printf("Enter month: ");
scanf("%d", &month);
printf("Enter the day of the week on which the month begins (0=Sun, 1=Mon, 2=Tue, etc.): ");
scanf("%d", &week_day);
// Check if the year is a leap year
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
days_in_month[1] = 29;
}
// Print the calendar header
printf("\n %d/%d\n", month, year);
printf("Su Mo Tu We Th Fr Sa\n");
// Print the days of the month
for (int i = 1; i <= days_in_month[month - 1]; i++) {
// Print spaces until we reach the first day of the month
if (i == 1) {
for (int j = 0; j < week_day; j++) {
printf(" ");
}
}
// Print the day of the month
printf("%2d ", i);
// Print a newline after Saturday
if ((i + week_day) % 7 == 0 || i == days_in_month[month - 1]) {
printf("\n");
}
}
return 0;
}
```
该代码使用了一个名为 `days_in_month` 的数组,用于存储每个月的天数。它还检查给定的年份是否为闰年,并相应地更新二月份的天数。接下来,该代码打印出月历的标题和星期几的缩写。然后,它打印出每一天,直到该月的最后一天。在打印日历的过程中,该代码使用了一个名为 `week_day` 的变量来跟踪该月份的第一天是星期几。