C++之日历
程序员文章站
2022-05-26 22:01:51
...
日历的元素
- 年月日
- 星期
如何加入星期元素?
提示:1900.1.1为星期一
以此类推,根据相差天数获得每个月第一天的星期数
#include <iostream>
using namespace std;
class Calendar {
private:
int year,month,day;
public:
Calendar() {
year = month = day = 0;
}
bool leapYear(int y) {
if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) return true;
else return false;
}
void setYear(int tmp) {
year = tmp;
}
void setSomeDay(int x,int y,int z) {
year = x;
month = y;
day = z;
}
int getDay(int m) {
if (m==1 || m==3 || m==5 || m==7 || m==8 || m==10 || m==12) return 31;
else if (m==4 || m==6 || m==9 || m==11) return 30;
else {
if (leapYear(year)) return 29;
else return 28;
}
}
//已知 1900.1.1 为星期一
int difYear() {
int dif = year - 1900;
int num = 0;
for (int i = 0; i < dif; ++i) {
if (leapYear(1900+i)) num += 366;
else num += 365;
}
return num;
}
int difDay() {
int dif = difYear();
for (int i = 0; i < month; ++i) {
dif += getDay(i);
}
dif += day;
return dif;
}
void printDay() {
int num = difDay()%7;
switch (num) {
case 1: cout << "Monday" << endl; break;
case 2: cout << "Thesday" << endl; break;
case 3: cout << "Wednesday" << endl; break;
case 4: cout << "Thurday" << endl; break;
case 5: cout << "Friday" << endl; break;
case 6: cout << "Saturday" << endl; break;
case 7: cout << "Sunday" << endl; break;
}
}
void printYear() {
int num = difYear();
for (int i = 1; i <= 12; ++i) {
cout << "Mon Tue Wed Thu Fri Sat Sun" << endl;
switch (i) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
for (int j = 0; j < num%7; ++j) cout << " ";
for (int k = 1,m = num%7 + 1; k <= 31; ++k,++m) {
if (k < 10) cout << k << " ";
else cout << k << " ";
if (m % 7 == 0) cout << endl;
}
cout << endl;
num += 31;
break;
case 4: case 6: case 9: case 11:
for (int j = 0; j < num%7; ++j) cout << " ";
for (int k = 1,m = num%7 + 1; k <= 30; ++k,++m) {
if (k < 10) cout << k << " ";
else cout << k << " ";
if (m % 7 == 0) cout << endl;
}
cout << endl;
num += 30;
break;
case 2:
if (leapYear(year)) {
for (int j = 0; j < num%7; ++j) cout << " ";
for (int k = 1,m = num%7 + 1; k <= 29; ++k,++m) {
if (k < 10) cout << k << " ";
else cout << k << " ";
if (m % 7 == 0) cout << endl;
}
cout << endl;
num += 29;
} else {
for (int j = 0; j < num%7; ++j) cout << " ";
for (int k = 1,m = num%7 + 1; k <= 28; ++k,++m) {
if (k < 10) cout << k << " ";
else cout << k << " ";
if (m % 7 == 0) cout << endl;
}
cout << endl;
num += 28;
}
}
}
}
};
int main () {
Calendar test;
test.setYear(2017);
test.printYear();
test.setSomeDay(2017,11,27);
test.printDay();
}
主要考虑距离多少天后如何得知第一天的星期数,用模运算即可
上一篇: 日历Calendar
下一篇: calendar日历