Hello, I've been having some trouble for my class assignment. I'm supposed to input a year and then it will output if the year is a leap-year or not.
A year with 366 days is called a leap year.
A year is a leap year if it is divisible by four (for example, 1980), except that it is not a leap year if it is divisible by 100 (for example, 1900); however, it is a leap year if it is divisible by 400 (for example, 2000).
There were no exceptions before the introduction of the Gregorian calendar on October 15, 1582 (1500 was a leap year).
Write a program that asks the user for a year and computes whether that year is a leap year.
if (number % 100 != 0)
{
if (number % 400 == 0)
{
contradict each other. That is if number % 100 != 0 then it is not a value that is divisible by 400. Also you have not enough ellse statements that to print messages that a year is not leap.
@freddy92
You don't want to nest the last if you have there, it should be part of an if...else if statement, like this:
1 2 3 4 5 6 7 8 9
if(number % 4 == 0)
{
if (number % 400 == 0)
// leap year
elseif (number % 100 == 0)
// not a leap year
else
//leap year
}
I would rewrite your code snip the following way
1 2 3 4 5 6 7 8
if ( number % 400 == 0 )
// leap year
elseif ( number % 100 == 0 )
// not a leap year
elseif ( number % 4 == 0 )
//leap year
else
// not a leap year
But in any case it is more simply to write
1 2 3 4 5 6 7 8
if ( number % 4 == 0 && ( number % 100 != 0 || number % 400 == 0 ) )
{
cout << "The year is a leap year." << endl;
}
else
{
cout << "The year isn't a leap year." << endl;
}
Or even the following way
1 2 3 4 5 6
auto IsLeap = []( int year )
{
return ( year % 4 == 0 && ( year % 100 != 0 || year % 400 == 0 ) );
};
cout << "The year is " << ( IsLeap( number ) ? "" : "not " ) << "a leap year." << endl;