C++ 分支语句练习----日期合法性

测试程序将随机给你一个格式为-连接了年、月、日的日期字符串(其中的数字都是没有前导零的,也就是说7不会被写成07)。你将需要判断这个日期在我们的公历体系内是否真实存在。如果存在则输出YES,否则输出NO

测试程序给出的测试输入数据中,年、月、日都是正整数(也就是大于零的整数),均不大于 5000。

已知,一年有 1 月~ 12 月,共 12 个不同的月份;其中 1 月、3 月、5 月、7 月、8 月、10 月、12 月有 31 个合法的日,分别为 1 日~ 31 日;4 月、6 月、9 月、11 月有 30 个合法的日,分别为 1 日~ 30 日。对于闰年,2 月有 29 个合法的日,分别为 1 日~ 29 日;对于平年(不是闰年的年称为平年),2 月有 28 个合法的日,分别为 1 日~ 28日。

闰年的判断则遵循如下依据:

  • 非整百年,能被4整除的为闰年。
  • 整百年,能被400整除的是闰年。

 样例输入:

2016-2-29

 样例输出:

YES

 最终代码:

#include <iostream>
using std::cout;
using std::endl;
using std::cin;

int main(){
   	char a;
	int year;
	int month;
	int day;
	bool leapyear = false;
	cin >> year >> a >> month >> a >> day;
	if ((year % 100 != 0 && year % 4 == 0)) {
		leapyear = true;
	}
	else if ((year % 100 == 0 && year % 400 == 0)) {
		leapyear = true;
	}
	if (month >= 1 && month <= 12) {
		if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
			if (day >= 1 && day <= 31) {
				cout << "YES" << endl;
			}
			else {
				cout << "NO" << endl;
			}
		}
		else if (month == 4 || month == 6 || month == 9 || month == 11 ){
			if (day >= 1 && day <= 30) {
				cout << "YES" << endl;
			}
			else {
				cout << "NO" << endl;
			}
		}
		else if(month == 2 && leapyear){
			if (day >= 1 && day <= 29) {
				cout << "YES" << endl;
			}
			else {
				cout << "NO" << endl;
			}
		}
		else {
			if (day >= 1 && day <= 28) {
				cout << "YES" << endl;
			}
			else {
				cout << "NO" << endl;
			}
		}
	}
	else {
		cout << "NO" << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_34970171/article/details/115646083