最近学习C++语言, 用的是《C++程序设计》这本书, 在做书上习题, 这是第五章第31题, 题目是:输入年份和这一年的第一天是星期几, 然后输出一整年的日历。由于是新手, 用了我大概一个多小时的时间。
这个代码是要求用户输入年份和这一年的第一天是星期几的, 当然也可以只输入年份, 星期几可以根据基姆拉尔森公式 计算, 不过我没有写在代码里。
下面代码在我的机器上运行是没有问题的, 我用的是Manjaro Linux, IDE是Clion。主要是记录个人的学习, 仅供个人日后参考, 如有错误, 还希望不吝赐教。
#include <iostream>
#include <iomanip>
#define WEEK 7
using namespace std;
int print_days(int whitespace, int days){
int count =0, day = 0;
while(whitespace != 0){
cout << setw(5) << " ";
whitespace--;
count++;
}
while(day < days){
if(count < WEEK - 1){
cout << setw(5) << day+1;
day++;
count++;
}
else{
cout << setw(5) << day+1 << endl;
day++;
count = 0;
}
}
return count;
}
int main(){
bool isLeap;
bool bigMonth = true;
bool feb = false;
int days = 31;
string months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
string weekdays[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
cout << "输入一个年份" << endl;
int year;
cin >> year;
cout << "请输入一个星期" << endl;
int week;
cin >> week;
isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
int month = 0;
int whitespace = week;
for (int m=0; m<12; m++){
int count = 0;
cout << setw(20) << months[month] << " " <<year << endl;
month++;
cout << " __________________________________ " << endl << endl;
for (int j=0; j < WEEK; j++){
cout << setw(5) << weekdays[j];
}
cout << endl;
if(bigMonth){
whitespace = print_days(whitespace, days);
// whitespace = count;
bigMonth = false;
if(month==7) bigMonth = true;
if(month==1) feb = true;
days = 30;
if(month==7) days = 31;
if(month==1) days = isLeap?29:28;
cout << endl << endl;
}
else if(!bigMonth && !feb){
whitespace = print_days(whitespace, days);
// whitespace = count;
bigMonth = true;
days = 31;
cout << endl << endl;
}
else{
whitespace = print_days(whitespace, days);
// whitespace = count;
feb = false;
bigMonth = true;
days = 31;
cout << endl << endl;
}
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/cbe6cb4b5fbef8ab87a5534f924b8df5.png)