华为机试 HJ73题解 | #计算日期到天数转换#
计算日期到天数转换
https://www.nowcoder.com/practice/769d45d455fe40b385ba32f97e7bcded
#include <iostream> #include <bits/stdc++.h> using namespace std; int GetDaysOfYear(int year, int month, int day) { int days = 0; bool isLeapYear = false; // 是否为闰年 if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { // 判断是否为闰年(能被4整除或者能被100整除但不能被400整除,则为闰年。闰年有366天;平年为365天) isLeapYear = true; } else { isLeapYear = false; } switch (month) { case 1: days = day; break; case 2: days = 31 + day; break; case 3: days += 31 + (isLeapYear ? 29 : 28) + day; break; case 4: days += 31 + (isLeapYear ? 29 : 28) + 31 + day; break; case 5: days += 31 + (isLeapYear ? 29 : 28) + 31 + 30 + day; break; case 6: days += 31 + (isLeapYear ? 29 : 28) + 31 + 30 + 31 + day; break; case 7: days += 31 + (isLeapYear ? 29 : 28) + 31 + 30 + 31 + + 30 + day; break; case 8: days += 31 + (isLeapYear ? 29 : 28) + 31 + 30 + 31 + +30 + 31 + day; break; case 9: days += 31 + (isLeapYear ? 29 : 28) + 31 + 30 + 31 + +30 + 31 + 31 + day; break; case 10: days += 31 + (isLeapYear ? 29 : 28) + 31 + 30 + 31 + +30 + 31 + 31 + 30 + day; break; case 11: days += 31 + (isLeapYear ? 29 : 28) + 31 + 30 + 31 + +30 + 31 + 31 + 30 + 31 + day; break; case 12: days += 31 + (isLeapYear ? 29 : 28) + 31 + 30 + 31 + +30 + 31 + 31 + 30 + 31 + 30 + day; break; default: break; } return days; } int main() { int year, month, day; while (cin >> year >> month >> day) { // 注意 while 处理多个 case cout << GetDaysOfYear(year, month, day) << endl; } }