|
发表于 2023-10-13 09:23:33
|
显示全部楼层
问题分析:
要判断一个日期是否合法,需要考虑以下几个方面:
1. 年份的范围:通常使用公历年份表示,可以限定在某个范围内(例如1900-2100)。
2. 月份的范围:合法的月份应介于1-12之间。
3. 不同月份的天数:不同月份有不同的天数,需要根据具体的年份和月份判断。
4. 闰年的处理:闰年的2月份有29天,平年只有28天。
根据以上分析,我们可以设计一个函数来判断日期是否合法。下面是使用C++实现的代码示例:
- #include <iostream>
- #include <sstream>
- #include <string>
- bool isLeapYear(int year) {
- return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
- }
- bool isValidDate(int year, int month, int day) {
- if (year < 1900 || year > 2100 || month < 1 || month > 12 || day < 1)
- return false;
- static const int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
- // 处理闰年的2月份
- if (month == 2 && isLeapYear(year))
- return day <= 29;
-
- return day <= daysInMonth[month - 1];
- }
- int main() {
- std::string input;
- std::getline(std::cin, input);
- std::stringstream ss(input);
- int year, month, day;
- // 从输入字符串中解析年、月、日
- ss >> year;
- ss.ignore(); // 跳过分隔符
- ss >> month;
- ss.ignore(); // 跳过分隔符
- ss >> day;
- if (isValidDate(year, month, day))
- std::cout << "YES" << std::endl;
- else
- std::cout << "NO" << std::endl;
- return 0;
- }
复制代码
代码说明:
1. isLeapYear()函数用于判断闰年,根据闰年的定义进行判断,返回true表示是闰年,返回false表示不是闰年。
2. isValidDate()函数用于判断日期是否合法。首先检查年份和月份的范围,然后根据月份和是否闰年来判断天数是否合法。
3. main()函数中,首先读取输入的日期字符串,然后使用std::stringstream进行解析,并传递给isValidDate()函数进行判断。最后根据判断结果输出"YES"或"NO"。
希望这个例子能帮助您理解如何在C/C++中判断日期的合法性。如果有任何疑问,请随时追问。
球一个最佳答案谢谢啦!这对我非常重要!   |
|