用c++编写一个测试计算下一天日期的函数nextDate()并加主函数可以运行
时间: 2024-02-25 18:51:14 浏览: 37
好的,以下是用C++编写的测试计算下一天日期的函数`nextDate()`和主函数:
```cpp
#include<iostream>
using namespace std;
bool isLeapYear(int year) //判断是否为闰年
{
if(year%400==0 || (year%4==0 && year%100!=0))
return true;
else
return false;
}
int nextDate(int year, int month, int day) //计算下一天日期
{
int daysInMonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
if(isLeapYear(year)) //闰年二月有29天
daysInMonth[1] = 29;
if(month<1 || month>12 || day<1 || day>daysInMonth[month-1])
return -1; //输入不合法,返回-1
if(day<daysInMonth[month-1])
return day+1; //同月,日数加1
else //要进入下一个月
{
if(month==12) //要进入下一年
return 101; //标记为新的一年的1月1日
else //要进入下一月
return 100+month+1; //标记为新的一月的1日
}
}
int main()
{
int year, month, day;
cout<<"请输入一个日期(格式:年 月 日):"<<endl;
cin>>year>>month>>day;
int nextday = nextDate(year, month, day);
if(nextday==-1)
cout<<"输入的日期不合法!"<<endl;
else if(nextday==101)
cout<<"明天是 "<<year+1<<" 年 1 月 1 日"<<endl;
else if(nextday>100) //新的一月
cout<<"明天是 "<<year<<" 年 "<<nextday-100<<" 月 1 日"<<endl;
else //同月
cout<<"明天是 "<<year<<" 年 "<<month<<" 月 "<<nextday<<" 日"<<endl;
return 0;
}
```
注意:这个函数对于非法输入会返回-1,对于新的一年的1月1日会返回101,对于新的一月的1日会返回标号为100+month+1的整数,其余情况会返回明天的日期。也就是说,如果返回值大于100,则代表明天是一个新月的第一天。
相关推荐
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)