C++ 日历表
日历描述:
输入要查询的年份和月份,输出对应的日历表。
代码思路:
先求出是否为瑞年或者平年,再求出每月多少天,最后再按照格式输出即可。
代码如下:
/*日历表--范裕昊*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
int year, i;
int month;
cout << "请输入年份:";
cin >> year;
cout << "请输入月份:";
cin >> month;
int sum = 0;
/*判断是否为瑞年*/
for (i = 1; i < year; i++){
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0){
sum += 366;
}
else{
sum += 365;
}
}
/*判断每月多少天*/
for (i = 1; i < month; i++) {
if (i == 2) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
sum += 29;//瑞年 29天
}
else {
sum += 28;//平年 28天
}
}
else {
if (i == 4 || i == 6 || i == 9 || i == 11) {
sum += 30; //4,6,9,11都为30天
}
else {
sum += 31; //剩下的都是31天
}
}
}
sum++;
/*开始对星期排序*/
int weakday = sum % 7;
cout << "要查询的日历如下:\n年份:" << year << "年\n月份:" << month <<"月"<<endl;
cout << "日\t一\t二\t三\t四\t五\t六" << endl;
/*求余并且添加空格对应*/
for (i = 1; i <= weakday; i++) {
cout << "\t";
}
/*对1,3,5,7,8,10月进行判断*/
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
for (i = 1; i <= 31; i++){
if (sum % 7 == 6) {
cout << i << "\n";
}
else{
cout << i << "\t";
}
sum++;
}
}
else{
/*对4,6,9,11月进行判断*/
if (month == 4 || month == 6 || month == 9 || month == 11){
for (int i = 1; i <= 30; i++){
if (sum % 7 == 6){
cout << i << "\n";
}
else{
cout << i << "\t";
}
sum++;
}
}
else{
/*对是否为瑞年的2月进行判断*/
/*瑞年*/
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0){
for (int i = 1; i <= 29; i++){
if (sum % 7 == 6){
cout << i << "\n";
}
else{
cout << i << "\t";
}
sum++;
}
}
else{
/*平年*/
for (int i = 1; i <= 28; i++){
if (sum % 7 == 6){
cout << i << "\n";
}
else{
cout << i << "\t";
}
sum++;
}
}
}
}
cout << endl;
getchar(); getchar();
return 0;
}
/*样例输入-输出如下*/
请输入年份:2018
请输入月份:2
要查询的日历如下:
年份:2018年
月份:2月
日 一 二 三 四 五 六
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28
请输入年份:2018
请输入月份:3
要查询的日历如下:
年份:2018年
月份:3月
日 一 二 三 四 五 六
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
请输入年份:2018
请输入月份:4
要查询的日历如下:
年份:2018年
月份:4月
日 一 二 三 四 五 六
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30