首页 > 解决方案 > 查找特定年份和闰年中的特定日期

问题描述

所以,我已经完成了这么多的程序,我仍然需要确定今年 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;
}

标签: c++

解决方案


  1. 使用modulo 算术运算符( %) 确定年份是否可被 4 整除。
    • 如果不是,那就不是飞跃。

请注意,operator%当且仅当 lhs 可被 rhs 整除时,结果等于 0。

  1. 然后,如您在问题中所描述的那样,应用相同的运算符,该运算符具有确定年份是否为闰的算法背后的逻辑。详细信息在我的答案代码的评论中。
[[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)
}

推荐阅读