题解 | #计算日期到天数转换#
计算日期到天数转换
http://www.nowcoder.com/practice/769d45d455fe40b385ba32f97e7bcded
1、 先判断此年是否为闰年,闰年比平年多一天,如果为闰年flag = 1, ret += 1
2、计算第n个月的天数,先计算 n - 1月的天数,循环遍历数组 ret += array[i];
3、一种额外情况,若此年份为2000/2/1就不再考虑ret+=1了,直接ret += day
#include<iostream> using namespace std; int main() { static int array[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 }; int year, month, day; int ret = 0, flag = 0; while (cin >> year >> month >> day) { if (year < 0 || month > 12 || day < 1 || day > 31 || ((month == 2) && day > 29)) { break; } int i = 0; while (i < month - 1) { ret += array[i]; i++; } if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) flag = 1; if(day > 1) ret += flag + day; ret += day; cout << ret << endl; } }