【疑点求解】C/C++的一道基础题
【疑问求解】C/C++的一道基础题
/*从2000年1月1日开始,计算第n天的年月日
输入:
1
1730
1740
输出:
2000-1-2
2004-9-26
2004-10-6
为什么我输入1730,总是差一天呢
*/
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
string week;
int year,month,day;
while(cin>>n && n!=-1)
{
if(n%7==0)week="Sunday";
else if(n%7==1)week="Monday";
else if(n%7==2)week="Tuesday";
else if(n%7==3)week="Wednesday";
else if(n%7==4)week="Thursday";
else if(n%7==5)week="Friday";
else if(n%7==6)week="Saturday";
year=2000;month=1;day=1;
//处理 年
while(n>=365)
{
if(year%4==0 && year%400!=0)
{
if(n>=366)
{
n-=366;
}
}
else
{
n-=365;
}
year++;
}
while(n>=28)//最低是2月的28天
{
if(n>=31&&(month==1||month==3||month==5||month==7||month==8||month==10||month==12))
{n-=31;month++;continue;}
else if(n>=30&&(month==4||month==6||month==9||month==11))
{n-=30;month++;continue;}
else if(month==2)//剩余一个2月
{
if((year%4==0 && year%400!=0)&& n>=29)
{
n-=29;
month++;
continue;
}
else if((!(year%4==0 && year%400!=0))&&n>=28)
{
n-=28;
month++;
continue;
}
}
break;
}
cout<<year<<"-"<<month<<"-"<<day+n<<" "<<week<<endl;
}
return 0;
}
------解决方案--------------------
闰年的条件是这个:
if(year%4==0 && year%100!=0||year%400==0)
/*从2000年1月1日开始,计算第n天的年月日
输入:
1
1730
1740
输出:
2000-1-2
2004-9-26
2004-10-6
为什么我输入1730,总是差一天呢
*/
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
string week;
int year,month,day;
while(cin>>n && n!=-1)
{
if(n%7==0)week="Sunday";
else if(n%7==1)week="Monday";
else if(n%7==2)week="Tuesday";
else if(n%7==3)week="Wednesday";
else if(n%7==4)week="Thursday";
else if(n%7==5)week="Friday";
else if(n%7==6)week="Saturday";
year=2000;month=1;day=1;
//处理 年
while(n>=365)
{
if(year%4==0 && year%400!=0)
{
if(n>=366)
{
n-=366;
}
}
else
{
n-=365;
}
year++;
}
while(n>=28)//最低是2月的28天
{
if(n>=31&&(month==1||month==3||month==5||month==7||month==8||month==10||month==12))
{n-=31;month++;continue;}
else if(n>=30&&(month==4||month==6||month==9||month==11))
{n-=30;month++;continue;}
else if(month==2)//剩余一个2月
{
if((year%4==0 && year%400!=0)&& n>=29)
{
n-=29;
month++;
continue;
}
else if((!(year%4==0 && year%400!=0))&&n>=28)
{
n-=28;
month++;
continue;
}
}
break;
}
cout<<year<<"-"<<month<<"-"<<day+n<<" "<<week<<endl;
}
return 0;
}
------解决方案--------------------
闰年的条件是这个:
if(year%4==0 && year%100!=0||year%400==0)