问题描述:
已知2007年1月1日为星期一。设计一函数按照下述格式打印2007年以后(含)某年某月的日历,2007年以前的拒绝打印。为完成此函数,设计必要的辅助函数也是必要的。
输入说明 :
两个整数,表示年和月,以空格分隔
输出说明 :
按照范例输出
注意各个位置的空格数目,特别是每一行的末尾是否有空格。
输入范例 :
2021 5
输出范例 :
Calendar 2021 - 05
Su Mo Tu We Th Fr Sa
---------------------
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
---------------------
思路:
考验咱格式化输出的本领
用cout.setf和cout.width基本都能解决
代码实现:
#include<bits/stdc++.h>
using namespace std;
bool IsRun(int year)
{
if(year%100==0)
{
return year%400==0;
}
return year%4==0;
}
int DayOfMonth(int year,int month)
{
if(month==4 || month==6 || month==9 || month==11)
return 30;
else if(month==2)
{
if(IsRun(year))
return 29;
else
return 28;
}
else
return 31;
}
int DayFrom07(int year,int month)
{
int res=0;
for(int i=2007;i<year;i++)
{
if(IsRun(i))
res+=366;
else
res+=365;
}
for(int i=1;i<month;i++)
{
res+=DayOfMonth(year,i);
}
return res;
}
int main()
{
int year,month;
cin>>year>>month;
int days = DayFrom07(year,month);
int firstDay=days%7+1;
int outDays=DayOfMonth(year,month);
string filler =month<10?"0":"";
cout<<"Calendar "<<year<<" - "<<filler<<month<<endl;
cout<<"---------------------"<<endl;
cout<<"Su Mo Tu We Th Fr Sa"<<endl;
cout<<"---------------------"<<endl;
cout.setf(ios::right);
for(int i=0;i<firstDay%7;i++)
{
cout.width(2);
cout<<""<<" ";
}
for(int i=1;i<=outDays;i++)
{
cout.width(2);
cout<<i<<" ";
if((firstDay+i)%7==0 && i!=outDays)
cout<<endl;
}
cout<<endl;
cout<<"---------------------"<<endl;
}