所以,我已经完成了这么多程序,我仍然需要确定 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;
}
最佳答案
- 使用
取模
arithmetic operator (%
) 来确定年份是否可以被 4 整除。- 如果不是,则不是飞跃。
Note that a result of
operator%
equals 0 if and only if lhs is dividable by rhs.
- 然后,如您在问题中所述,应用相同的运算符和支持确定年份是否为闰年的算法背后的逻辑。 详细信息在我的答案代码的注释中。
[[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)
}
关于c++ - 查找特定年份和闰年的特定日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56516654/