Fred Enator
Fred Enator

Reputation: 27

C# Leap year check

I'm trying to make a program that shows the amount of days in a month, and I need to add leap years, so I've asked for the year and the way I'm trying to figure out the leap year is to check if the year is a multiple of 4, it says that it "cannot take the address of the given expression". Here is my code:

 if (month == 2)
      Console.WriteLine("\nThere are 28 days in Febuary");

 if (month == 2) &(4%year);
      Console.WriteLine("\nThere are 29 days in Febuary this year as it is a leap year");

Upvotes: 0

Views: 3016

Answers (4)

Clive Ciappara
Clive Ciappara

Reputation: 558

You need to change the code as follows:

if (month == 2 && DateTime.IsLeapYear(year))
    Console.WriteLine("\nThere are 29 days in Febuary this year as it is a leap year");
else if (month == 2)
    Console.WriteLine("\nThere are 28 days in Febuary");

What was changed?

  • You had a semi-colon at the end of the second if statement
  • Move the month == 2 as the second if statement, as it will always enter the first if when month is February
  • Use else if, else it will enter both if statements and write down the two statements

(Added suggestions from @waka and @TheSkimek, thanks!)

Upvotes: 0

Izuka
Izuka

Reputation: 2612

Your syntax for your second if is totally incorrect here. First, adding a ; at the end of the if condition means that you are simply doing nothing after checking your condition. Second, you used the & operator which returns the address of an operand, leading to the error you just had. You wanted to use the && operator here. Finally, just set your whole condition in the same pair of parenthesis.

Also, make sure to check about what is exactly a leap year. According to Wikipedia:

Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100, but these centurial years are leap years if they are exactly divisible by 400. For example, the years 1700, 1800, and 1900 were not leap years, but the years 1600 and 2000 were.

In the end, your corrected if would give:

if (month == 2 && year % 4==0 && (year % 100 != 0 || year % 400 == 0))
    Console.WriteLine("\nThere are 29 days in Febuary this year as it is a leap year");

Upvotes: 2

Enigmativity
Enigmativity

Reputation: 117029

The correct code you need to determine a leap year is:

if (month == 2)
{
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
    {
        Console.WriteLine("\nThere are 29 days in Febuary this year as it is a leap year");
    }
    else
    {
        Console.WriteLine("\nThere are 28 days in Febuary");
    }
}

Leap years occur on year divisible by 4 unless they are divisible by 100 unless they are divisible by 400.

Upvotes: 1

TheSkimek
TheSkimek

Reputation: 342

Use:

DateTime.IsLeapYear(year)

Upvotes: 5

Related Questions