万年历代码

#include 
#include 
using namespace std;

// 判断是否为闰年
bool isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

// 获取每月的天数
int getDaysInMonth(int year, int month) {
    int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (month == 2 && isLeapYear(year))
        return 29;
    return days[month - 1];
}

// 计算从1900年1月1日到指定日期的总天数
int getTotalDays(int year, int month) {
    int total = 0;
    
    // 计算整年的天数
    for (int y = 1900; y < year; y++) {
        if (isLeapYear(y))
            total += 366;
        else
            total += 365;
    }
    
    // 加上当年经过的月份的天数
    for (int m = 1; m < month; m++) {
        total += getDaysInMonth(year, m);
    }
    
    return total;
}

void printCalendar(int year, int month) {
    cout << "\n---------------" << year << "年" << month << "月---------------\n";
    cout << "一  二  三  四  五  六  日\n";
    
    // 计算该月第一天是星期几
    int startWeekday = (getTotalDays(year, month) + 1) % 7;
    
    // 调整星期日的位置(从0变成7)
    if (startWeekday == 0) {
        startWeekday = 7;
    }
    
    // 打印前导空格
    for (int i = 1; i < startWeekday; i++) {
        cout << "    ";
    }
    
    // 打印日期
    int daysInMonth = getDaysInMonth(year, month);
    for (int day = 1; day <= daysInMonth; day++) {
        cout << setw(2) << day << "  ";
        if ((startWeekday + day - 1) % 7 == 0)
            cout << endl;
    }
    cout << "\n";
}

int main() {
    int year, month;
    
    while (true) {
        cout << 1900-2100 cin>> year;
        if (year < 1900 year> 2100) {
            cout << "年份超出范围,请重新输入!\n";
            continue;
        }
        
        cout << 1-12 cin>> month;
        if (month < 1 month> 12) {
            cout << "月份无效,请重新输入!\n";
            continue;
        }
        
        printCalendar(year, month);
        
        char choice;
        cout << yn cin>> choice;
        if (choice != 'y' && choice != 'Y')
            break;
    }
    
    return 0;
}

可在devc++运行

原文链接:,转发请注明来源!