24/5/15 C语言日历打印
24/5/15输入1970年之后任意一年的年份,输出该年的年历
一、前言`
在现在实现的打印日历前,设置了判断闰年,计算从1970/1/1至输入的日期的总天数,对应月总天数,判断输入日期几这几个函数。
总结:在完成需求时,不应该把内容都写在main里,而应该分成几个函数来写。后续添加和调整实现功能会更灵活。
输出样例:
二、代码
代码如下(示例):
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdbool.h>
//判断是否是闰年
bool isleapyear(int year)
{
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
//获取该月的天数
int get_days_in_month(int year, int month) {
if (month == 2)
{
if (isleapyear(year)) {
return 29;
}
else
{
return 28;
}
}
else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
}
else
{
return 31;
}
}
//总天数
int sum_days(int year,int month,int day) {
int sumday=0;
for (int i = 1970; i < year; i++) {
if (isleapyear(i))
{
sumday = sumday + 366;
}
else
{
sumday = sumday + 365;
}
}
for (int i = 1; i < month; i++) {
sumday = sumday + get_days_in_month(year, i);
}
sumday = sumday + day;
return sumday;
}
//星期几
int get_weekday(int year, int month, int day)
{
int weekday = (sum_days(year, month, day)+3 )% 7 ;
if (weekday != 0) {
return weekday;
}
else {
return 7;
}
}
print_year_calender(int year) {
printf("=========%d的日历如下=========\n", year);
const char* month[] = {
"", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
for (int i = 1; i < 13; i++)
{
printf("\n%s\n", month[i]);
printf("\n SUN MON TUS WED THU FRI SAT \n");
//每月第一天是周几
int weekday_of_fday = get_weekday(year, i, 1);
//打印每月第一天前的空格
for (int j = 0; j < weekday_of_fday; j++)
{
printf(" ");
}
//获取总天数
int days = get_days_in_month(year, i);
//打印格式
for (int day = 1; day <= days; day++)
{
printf("%4d", day);
if ((weekday_of_fday + day ) % 7==0 || day == days)
{
printf("\n");//确定日历换行位置
}
}
printf("==============================\n");
}
}
int main(void) {
int year, month, day;
int week = 0;
printf("请输入一个年份:\n");
scanf("%d", &year);
/*
printf("请输入一个日期:\n");
scanf("%d/%d/%d", &year, &month, &day);
printf("从1970年1月1日到%d年%d月%d日总天数为%d\n", year, month, day, sum_days(year, month, day));
printf("星期%d\n", get_weekday(year, month, day));
*/
print_year_calender(year);
return 0;
}
---