c++ - 查找特定年份和闰年中的特定日期
问题描述
所以,我已经完成了这么多的程序,我仍然需要确定今年 1 月 1 日是一周中的哪一天以及闰年:闰年是一个数字可以被 4 整除的年份。然而,世纪年只有当它们能被 400 整除时才是闰年。因此 1900 年不是闰年,但 2000 年是闰年。我有点坚持从这里去哪里,我在脑海中理解它,但在将我的想法转化为代码时遇到了麻烦。如果有人可以将我推向正确的方向,或者您有解决方案,我真的很感谢您的帮助。
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
tm dateTime;
time_t systemTime = time(0);
localtime_s( &dateTime, &systemTime );
int day = dateTime.tm_mday;//theTime.tm_mday;
int month = dateTime.tm_mon+1;//theTime.tm_mon;
int year = dateTime.tm_year + 1900;//theTime.tm_year + 1900;
int weekDay = dateTime.tm_wday;
cout << "Today is ";
switch (weekDay){
case 0: cout << "Sunday, ";
break;
case 1: cout << "Monday, ";
break;
case 2: cout << "Tuesday, ";
break;
case 3: cout << "Wednesday, ";
break;
case 4: cout << "Thursday, ";
break;
case 5: cout << "Friday, ";
break;
case 6: cout << "Saturday, ";
break;
}
cout << month << "/" << day << "/" << year << endl;
}
解决方案
- 使用
modulo
算术运算符(%
) 确定年份是否可被 4 整除。- 如果不是,那就不是飞跃。
请注意,
operator%
当且仅当 lhs 可被 rhs 整除时,结果等于 0。
- 然后,如您在问题中所描述的那样,应用相同的运算符,该运算符具有确定年份是否为闰的算法背后的逻辑。详细信息在我的答案代码的评论中。
[[nodiscard]]
constexpr bool IsLeap(const int & Year) noexcept
{
// If $Year is not dividable by 4, it's not leap, eg 2003.
// Otherwise, apply more logic below (for years like 2004, 2000 or 1900).
if (Year % 4 != 0) [[likely]]
return false;
// If $Year is dividable by 100, eg 2000, check if it's also dividable by 400.
// If it's also dividable by 400, it's leap, eg 2000.
// Otherwise, it's not leap, eg 1900.
if (Year % 100 == 0) [[unlikely]]
{
if (Year % 400 == 0) [[unlikely]]
return true;
return false;
}
// $Year is dividable by 4 and not by 100, so it's leap.
return true;
}
例子:
#include <iostream>
int main()
{
std::cout << std::boolalpha << IsLeap(2003) << std::endl; // false (not dividable by 4)
std::cout << std::boolalpha << IsLeap(2004) << std::endl; // true (dividable by 4 and not dividable by 100)
std::cout << std::boolalpha << IsLeap(2000) << std::endl; // true (dividable by 4, 100 and 400)
std::cout << std::boolalpha << IsLeap(1900) << std::endl; // false (dividable by 4 and 100, but not by 400)
}
推荐阅读
- ruby - 如何收集功能文件的所有标签?
- azure-active-directory - 服务主体和 CRL 检查
- python - C:\Python\python.exe: 无法打开文件'
': [Errno 2] 没有这样的文件或目录 - python - Python 仅在 SQLite DB 上插入一行
- r - R stargazer 将几个回归模型堆叠成行
- c++ - 我应该如何处理:错误 C2039 'assign': is not a member of 'cl::string' in Visual Studio 2017?
- python - 如何修复 XMLSyntaxError:标签中的数据过早结束
- reactjs - npm run build - 编译失败 - 无法读取未定义的属性“toLowerCase”
- xpages - XPages:一个模板,两个内存模型?
- routes - 以最快的路由获胜的骆驼多播聚合