判断日期是否是合法的:
需要判断这个日期在我们的公历体系内是否真实存在。如果存在则输出YES,否则输出NO。
已知,一年有 1 月~ 12月,共 12 个不同的月份;其中 1 月、3月、5 月、7 月、8 月、10 月、12月有 31个合法的日,分别为 11 日~ 31 日;4月、6 月、99月、11月有 30个合法的日,分别为 1 日~ 30 日。对于闰年,2 月有 29 个合法的日,分别为 1 日~ 29 日;对于平年(不是闰年的年称为平年),2月有 2 个合法的日,分别为 1日~ 28日。
闰年的判断则遵循如下依据:
非整百年,能被4整除的为闰年。
整百年,能被400整除的是闰年。
1 2#include <iostream> 2 2 using std::cin; 3 3 using std::cout; 4 4 using std::endl; 5 5 int main() 6 6 { 7 7 int year; 8 8 int month; 9 9 int day; 10 10 char op = '-'; 11 11 cin >> year >> op >> month >> op >> day; 12 12 if (year % 100 == 0 && year % 400 == 0) 13 13 { 14 14 if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) 15 15 { 16 16 if (day >= 1 && day <= 31) 17 17 { 18 18 cout << "YES"; 19 19 } 20 20 else 21 21 { 22 22 cout << "NO"; 23 23 } 24 24 } 25 25 else if (month == 4 || month == 6 || month == 9 || month == 11) 26 26 { 27 27 if (day >= 1 && day <= 30) 28 28 { 29 29 cout << "YES"; 30 30 } 31 31 else 32 32 { 33 33 cout << "NO"; 34 34 } 35 35 } 36 36 else if(month==2) 37 37 { 38 38 if (day >= 1 && day <= 29) 39 39 { 40 40 cout << "YES"; 41 41 } 42 42 else 43 43 { 44 44 cout << "NO"; 45 45 } 46 46 } 47 47 else 48 48 { 49 49 cout << "NO"; 50 50 } 51 51 } 52 52 53 53 else if (year % 100 != 0 && year % 4 == 0) 54 54 { 55 55 if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) 56 56 { 57 57 if (day >= 1 && day <= 31) 58 58 { 59 59 cout << "YES"; 60 60 } 61 61 else 62 62 { 63 63 cout << "NO"; 64 64 } 65 65 } 66 66 else if (month == 4 || month == 6 || month == 9 || month == 11) 67 67 { 68 68 if (day >= 1 && day <= 30) 69 69 { 70 70 cout << "YES"; 71 71 } 72 72 else 73 73 { 74 74 cout << "NO"; 75 75 } 76 76 } 77 77 else if(month == 2) 78 78 { 79 79 if (day >= 1 && day <= 29) 80 80 { 81 81 cout << "YES"; 82 82 } 83 83 else 84 84 { 85 85 cout << "NO"; 86 86 } 87 87 } 88 88 89 89 else 90 90 { 91 91 cout << "NO"; 92 92 } 93 93 } 94 94 95 95 else 96 96 { 97 97 if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) 98 98 { 99 99 if (day >= 1 && day <= 31) 100 100 { 101 101 cout << "YES"; 102 102 } 103 103 else 104 104 { 105 105 cout << "NO"; 106 106 } 107 107 } 108 108 109 109 else if (month == 4 || month == 6 || month == 9 || month == 11) 110 110 { 111 111 if (day >= 1 && day <= 30) 112 112 { 113 113 cout << "YES"; 114 114 } 115 115 else 116 116 { 117 117 cout << "NO"; 118 118 } 119 119 } 120 120 121 121 else if(month == 2) 122 122 { 123 123 if (day >= 1 && day <= 28) 124 124 { 125 125 cout << "YES"; 126 126 } 127 127 else 128 128 { 129 129 cout << "NO"; 130 130 } 131 131 } 132 132 else 133 133 { 134 134 cout << "NO"; 135 135 } 136 136 } 137 137 138 138 return 0; 139 139 }