C语言实现简易日历

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43669941/article/details/84404373
#include <iostream>
#include <iomanip>
using namespace std;

//计算闰年多出来一天的总天数
int foo (int year) {
	return year/4 - year/100 + year /400;
}

//计算总天数
int total_days(int year, int month, int day, int* m) {
	int _month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};	
	int i, days = 0;
	days = (year-1)*365 + foo(year);
	
	for (i = 0; i<month-1; i++) {
		days += _month[i];
	}
	days += day;
	
	//除去闰年中2月份多的一天(以2月1日计算,总天数多加了29号这一天, 所以减去这一天)
	if(month<=2&&(year%400==0 || (year%100!=0&&year%4==0))) {
		days--;
		
		//如果该月刚好为2月且为闰年,天数返回29 
		if(month==2) {
			*m = 29;
		} else {
			
			//该月为1月
			*m = 31;
		}
		
	} else {
		*m = _month[month-1];
	}
	return days;
}

int main(void) {
	int year, month, firstday, i, j;
	cout << " 请输入需要获取的年月:";
	cin >> year;
	cin >> month;
	
	cout << setw(4) << year << "-" << month << ":" << endl;
	
	firstday = total_days(year, month, 1, &month)%7;//计算这个月的第一天是星期几
	if (firstday == 0) {
		firstday = 7;
	}
	
	cout << "\t一  二  三  四  五  六  日\n\t";
	
	//初始化第一天的位置
	for (i = 0; i < firstday-1; i++) {
		cout << "    ";
	}
	
	//输出日历
	for (i = 1; i <= month; i++) {
		if ((i + firstday - 2)%7==0) {
			cout << endl << "\t";
		}
		cout << setw(2) << i << "  ";
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43669941/article/details/84404373