Find the next leap year in C [closed]

限于喜欢 提交于 2021-02-05 12:27:51

问题


I'm having trouble with an exercise on my homework. I have to make a function that tells me when the next leap year is given an n (or n if it's a leap year).

I already tackled the last part, but I'm having trouble with the "next leap year" part. I assume I have to do a cycle?

Here's what I have so far

int next_leapyear(int n) 
{

    if(((n%4==0)&&(n%100!=0))||(n%400==0)) return n;

    else
    while(?){
      n++;
     }

     return n;
}

I'm just starting to learn this language, so if you guys could keep it simple I would appreciate it


回答1:


Increase n until your if statement condition is not true so there are 2 ways either you can put condition in while braces, which is straight forward.

2nd is that, run loop infinite times and put breaking condition inside the loop

while(1){
      n++;
if(((n%4==0)&&(n%100!=0))||(n%400==0)) break;

     }



回答2:


The task could be split into two parts. First, one could check whether a given n is a leap year, which coule be done with the following function.

int IsLeapYear(int n)
{
    return (((n%4==0)&&(n%100!=0))||(n%400==0));
}

Next, one could use a loop, based on the function above, to increase n until it is a leap year. This could be done as follows.

int GetNextLeapYear(int n)
{
    int CurrentYear = n;
    while(!IsLeapYear(CurrentYear))
    {
        CurrentYear++;
    }
    return CurrentYear;
}



回答3:


Your idea of increasing the year until it's a leap year will work but it's not very efficient because you have to do a lot of modulos which is a very expensive operations.

In fact to find the next normal leap year you just need to round the year to the next multiple of 4, which can be achieved with either of these

year = (year + 3) & ~0x03;
year = (year | 0x03) + 1;

In case the after rounded it's a multiple of 100 then just add 4 to get the correct year. So the implementation may be like this

int next_leapyear(int n)
{
    n = (n + 3) & ~3;
    if (n % 100 == 0) n += 4;
    return n;
}


来源:https://stackoverflow.com/questions/46746157/find-the-next-leap-year-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!