Leap year calculation in C++ for Homework assignment?

user1698658 picture user1698658 · Sep 26, 2012 · Viewed 17.8k times · Source
#include <iostream>
using namespace std;

int main() {
    int what_year;

    cout << "Enter calendar year ";
    cin >> what_year;

    if (what_year - (n * 4) = 0 ) {

        cout << "leap year";
    }

    else
    {
        cout << "wont work";
    }

    system("Pause");
    return 0;
}

Trying to make a program for class, to find a leap year.. not sure how to ask C++ if an integer is divisible by a number?

Answer

Eric J. picture Eric J. · Sep 26, 2012

The leap year rule is

 if year modulo 400 is 0 then
   is_leap_year
else if year modulo 100 is 0 then
   not_leap_year
else if year modulo 4 is 0 then
   is_leap_year
else
   not_leap_year

http://en.wikipedia.org/wiki/Leap_year#Algorithm

You can use the modulo operator to see if one number is evenly divisible by another, that is if there is no remainder from the division.

2000 % 400 = 0 // Evenly divisible by 400

2001 % 400 = 1 // Not evenly divisible by 400

Interestingly, several prominent software implementations did not apply the "400" part, which caused February 29, 2000 not to exist for those systems.