检测闰年时遇到问题

时间:2014-04-26 05:35:37

标签: c++ epoch leap-year

再次,avHi, 谢谢大家对我以前的问题的帮助。

但是现在我遇到了另一个问题

int main ()
    {
        int inputSeconds,seconds, minutes, hours , days ,years ;
        int remainingSeconds ;
        int current_year = 1970;
        int current_month = 1;
        int current_day = 1;
        const int standard_year = 365;
        const int leap_year = 366;
        bool leapYear;
        int leapcounter  ; //Since 1972 is the next closest leap year, counter is set to 2


        cout << "Welcome to Epoch time/ Data converter" << endl;
        cout << "Enter Number of Seconds Since Midnight Jan 1, 1970: ";
        cin >> inputSeconds ;


        //Convert seconds into days to determine the number of years that has already passed


        days = inputSeconds/(60*60*24) ;
        remainingSeconds = inputSeconds % (60*60*24) ;


        cout << days << endl; 
        //Determine current year 

            while (!(days < 365))
            {
            if (leapcounter == 3 )
                {
                    current_year++;
                    days -= leap_year;
                    leapYear = true;
                    leapcounter = 0;

                }
            else
                {


                    current_year++;
                    days -= standard_year;
                    leapcounter++;  
                    leapYear = false;

                }
            } 


            //Check if current year is leap year or not

            if ((current_year % 4 == 0) && (current_year % 100 == 0) || (current_year % 400 == 0))
                leapYear = true;
            else
                leapYear = false;



        cout << current_year << " days remaining :" << days << " Leap year? " << leapYear << " Remaining seconds :" << remainingSeconds;

        return 0;

}

它似乎没有检测到输出的闰年。 我曾尝试过1972年,2004年,2008年和2012年。

我似乎无法弄清楚它的问题,并希望你能帮助解决我的问题 先感谢您。

2 个答案:

答案 0 :(得分:1)

current_year决定闰年的逻辑比你的更复杂。

需要:

if ((current_year % 4 == 0) )
{
  if ( (current_year % 100 == 0) )
  {
     if ( (current_year % 400 == 0) )
     {
        leapYear = true;
     }
     else
     {
        leapYear = false;
     }
  }
  else
  {
     leapYear = true;
  }
}
else
{
  leapYear = false;
}

进一步思考,这个逻辑可以简化为:

leapYear = ( (current_year % 400) == 0 ||
             ( (current_year % 4) == 0 && (current_year % 100) != 0)) ;

此外,您需要将leapcounter初始化为2,因为第1天对应于1970的第一天 - 自上一个闰年以来的2年。

答案 1 :(得分:0)

你走了:

bool IsALeapYear(int year) {
    return (!(year % 4) && (year % 100)) || !(year % 400);
}