Checking for Interger in C for Leap Years

  • Thread starter Thread starter madmike159
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
9 replies · 2K views
madmike159
Gold Member
Messages
369
Reaction score
0
I am making a program in C to tell the user what day of the week at date will be (eg. 1st Jan 2000 is a Saturday).
I need to account for leap years, the rule for them is below.

All years divisible by 4 are leap years unless the year can be divided by 100. There is, however, an exception to this 100 year rule exception. Any year that can be divided by 400 is a leap year. So while the years 1700, 1800 and 1900 were not leap years because they are divisible by 100, the year 2000, because it is divisible by 400, was a leap year.

I can divide the year 2001 by for and get 500.24, but how can I know that its not a interger?
 
Physics news on Phys.org
CompuChip's reply about the "modulus" operator should work perfectly.

If you are unfamiliar with typecasting [ like "(int)" ] you might want to look into that, although your current problem seems to be solved.
 
I found something on type casting (I had a lecture on it last week...)
if (year/4 == (int)year);

I forgot the remainder operator even existed.
Thanks for the help guys.
 
madmike159 said:
if (year/4 == (int)year);

No idea what was your plan, but that would not check if the year is leap.

8/4 = 8 ?
 
You could check whether the float division gives the same answer as the integer divison. I.e., something like

(float)year/4.0 == (float)((int)year/4)

However, this is ugly (the modulo operator makes it immediately clear what is meant) and risky (the float division of 2001/4 may give 500.2499999 while the integer division cast to float gives 500.250000..., and the comparison fails).
 
No that code worked, I tested it out. It checks if year would go into a int, if its true the if statement will run.
 
There seem to be loads of ways of doing this. I'm just going to test a few and see which is best. Thanks for the help guys.