Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leap year calculation in C++ for Homework assignment?

Tags:

c++

leap-year

#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?

like image 667
user1698658 Avatar asked Sep 25 '12 22:09

user1698658


2 Answers

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.

like image 145
Eric J. Avatar answered Oct 18 '22 19:10

Eric J.


Use the modulo function.

if ((year % 4) == 0)
{
//leap year
}

Note that this does not account for the 100 and 400 year jump.

Proper code would be something like

if(((year%4) == 0) && (((year%100)!=0) || ((year%400) == 0))
{
//leap year
}
like image 25
SinisterMJ Avatar answered Oct 18 '22 18:10

SinisterMJ