Efficient algorithm for converting number of days to years (including leap years)

后端 未结 10 2003
逝去的感伤
逝去的感伤 2021-02-05 17:04

The problem

I am writing a class for holding dates in c++, and I found the following problem:

I have a number of days N since a reference date (in

10条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-05 17:42

    This

    bool IsLeapYear(int year) 
    { 
        if ((year % 4 == 0) && (year % 100 != 0) && (year % 400 == 0)) return true; 
        else return false; 
    }
    

    is incorrect. It returns false for 2000. Better:

    bool IsLeapYear(int year) 
    { 
        if (year % 400 == 0) return true; 
        if ((year % 4 == 0) && (year % 100 != 0)) return true; 
        return false; 
    }
    

提交回复
热议问题