#include <iostream>
using namespace std;
class CDate {//定义一个名为CDate的类
public:
void setDate(int year, int month, int day) {//内联函数,向私密数据传递参数
Year = year;
Month = month;
Day = day;
}
void increaseDate(int a, int b, int c);//成员函数,用于天数加一
void showDate();//成员函数,用于输出新天数
private:
int Year;
int Month;
int Day;
};
inline void CDate::showDate()
{
cout << Year << "/" << Month << "/" << Day << endl;
}
void CDate::increaseDate(int a, int b, int c)
{
if ((a % 4 == 0 && a % 100 != 0) || (a % 400 == 0))//首先判断是否为闰年
{
if (b == 2)//然后判断是否是二月
{
if (c == 29) {
Year = a;
Month = b + 1;
Day = 1;
}
else
{
Year = a;
Month = b;
Day = c + 1;
}
}
else if (b == 1 || b == 3 || b == 5 || b == 7 || b == 8 || b == 10 )//如果是大月,则一个月有31天
{
if (c == 31)
{
Year = a;
Month = b + 1;
Day = 1;
}
else
{
Year = a;
Month = b;
Day = c + 1;
}
}
else if (b == 4 || b == 6 || b == 9 || b == 11)//如果是小月则一个月30天
{
if (c == 30)
{
Year = a;
Month = b + 1;
Day = 1;
}
else
{
Year = a;
Month = b;
Day = c + 1;
}
}
else
{
if (c == 31)
{
Year = a + 1;
Month = 1;
Day = 1;
}
else
{
Year = a;
Month = b;
Day = c + 1;
}
}
}
else//不是闰年的情况,只有2月和上面不同
{
if (b == 2)
{
if (c == 28) {
Year = a;
Month = b + 1;
Day = 1;
}
else
{
Year = a;
Month = b;
Day = c + 1;
}
}
else if (b == 1 || b == 3 || b == 5 || b == 7 || b == 8 || b == 10)
{
if (c == 31)
{
Year = a;
Month = b + 1;
Day = 1;
}
else
{
Year = a;
Month = b;
Day = c + 1;
}
}
else if (b == 4 || b == 6 || b == 9 || b == 11)
{
if (c == 30)
{
Year = a;
Month = b + 1;
Day = 1;
}
else
{
Year = a;
Month = b;
Day = c + 1;
}
}
else
{
if (c == 31)
{
Year = a + 1;
Month = 1;
Day = 1;
}
else
{
Year = a;
Month = b;
Day = c + 1;
}
}
}
}
int main()
{
int x, y, z;
while (cin >> x >> y >> z)//多组输入
{
CDate riqi;//初始化内部数据
riqi.setDate(x, y, z);
riqi.increaseDate(x, y, z);
riqi.showDate();
}
}
这道题我是用的最笨的办法,用if、else来判断大月、小月、和2月的天数不同的情况。还可以使用数组 or switch的方法来进行求解
数组代码如下
#include<iostream>
using namespace std;
int a[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
class CDate{
public:
void setDate(int y, int m, int d);
void increaseDate();
void showDate();
~CDate(){};
private:
int year, month, day;
};
void CDate::setDate(int y, int m, int d){
year = y;
month = m;
day = d;
};
void CDate::increaseDate(){
a[2] = (!(year % 4) && (year % 100) || !(year % 400) ? 29: 28);
if (++day > a[month]) day = 1, month++;
if(month > 12) month = 1, year++;
};
void CDate::showDate(){
cout << year << "/" << month << "/" << day << endl;
};
int main()
{
CDate i;
int year, month, day;
while(cin >> year >> month >> day){
i.setDate(year, month, day);
i.increaseDate();
i.showDate();
}
return 0;
}