题解 | #计算日期到天数转换#
计算日期到天数转换
https://www.nowcoder.com/practice/769d45d455fe40b385ba32f97e7bcded
#include <cmath> #include <iostream> using namespace std; bool isleap(int year) { return (year%4==0&&year%100!=0)||year%400==0; } //根据年与月返回当月的天数 int GetDaysByYM(int year,int month) { int days[13]={29,31,28,31,30,31,30,31,31,30,31,30,31}; if(month==2&&isleap(year)) { month=0; } return days[month]; } //根据年月日返回当前日期是当年的第几天 int GetdateByYMD(int year,int month,int day) { int days=0; //循环加上月数减一的整天数 for(int i=1;i<month;++i){ days+=GetDaysByYM(year,i); } //最后加上当月已经过的天数day days+=day; return days; } int main() { int year,month,day; while (cin >> year >> month>>day) { day=GetdateByYMD(year,month,day); cout<<day<<endl; } }