Reputation: 59
#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?
Upvotes: 5
Views: 18228
Reputation: 11
According to some rules that decide whether a year is leap or not, a year should be divisible by 4 and for those years that are divisible by 100, it should also be divisible by 400.
int year;
cout << "Enter a year: ";
cin >> year;
if (year%4 == 0) {
if (year%100 == 0) {
if (year%400 == 0) {
cout << year << " is a leap year.";
}
else {
cout << year << " is not a leap year.";
}
}
else {
cout << year << " is a leap year.";
}
}
else {
cout << year << " is not a leap year.";
}
return 0;}
Upvotes: 1
Reputation: 21351
Use this instead
bool bLeapYear = false;
if ((what_year % 4) ==0) {
if ((what_year % 100) == 0) {
bLeapYear = ((what_year % 400) == 0);
} else {
bLeapYear = true;
}
// leap year
}
This takes the remainder of the year after dividing by 4 and tests to see if it is zero. You also had a problem using =
instead of ==
- the latter tests for equality, the former assigns a value.
EDIT: Edited according to the comment of Steve below.
Upvotes: 4
Reputation: 150108
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.
Upvotes: 9
Reputation: 3509
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
}
Upvotes: 4