0

int main()

{

int month, year;
cout << "Enter a month (1-12) and year (1-2100): ";
cin >> month >> year;


if ((year > 2100 || year < 1) || (month > 12 || month < 1))
{
    cout << "Invalid Date";
}
else
{
     if ((month == 2) && (year % 100 == 0 && year % 400 == 0))
    {
        cout << "This month has 29 days";
    }
    else if ((month == 2) && (year % 100 != 0) && (year % 4 == 0))
    {
        cout << "This month has 29 days";
    }
    else if (month == 2)
    {
        cout << "This month has 28 days";
    }
    else if (month == 1, 3, 5, 7, 8, 10, 12)
    {
        cout << "This month has 31 days";
    }
    else if (month == 4, 6, 9, 11)
    {
        cout << "This month has 30 days";
    }
}


return 0;

}

I am trying to tell the user how many days are in the month that they have entered. The first if and else-if in the nested else is meant to determine whether or not the year the user entered is a leap year, if it is, and the month is 2, then the code will display 29 days. This seems to be working ok.

My problem is when I try to enter the months of 4, 6, 9, 11. aka the months with 30 days. The result i 31 days. It seems to not be reading the last else-if statement, but I don't understand why it wouldn't.

  • `if (month == 1, 3, 5, 7, 8, 10, 12)` that doesn't work. You need something like `if ((month == 1) || (month == 3) ...)`. Or better yet, a `switch` statement. – Blaze Feb 11 '20 at 07:45
  • What you want: https://www.fluentcpp.com/2020/01/03/dry-comparisons-a-c-library-to-shorten-redundant-if-statements/ – JVApen Feb 11 '20 at 07:46
  • 2
    `(month == 1, 3, 5, 7, 8, 10, 12)` is equivalent to `(12)` – PooSH Feb 11 '20 at 07:48
  • 1
    @PooSH Which in turn is equivalent to _not 0_, which is equivalent to true. – Frederik Juul Feb 11 '20 at 08:53
  • What you can do by the way instead of spaghetti-code statements or switch statements: Write a couple of functions like "OneOfThose(month, {2, 4, 6}). The second parameter will be a so called "initializer list" which does allow such a series of values separated by comma. That function should just loop over that list and compare with the first parameter to return whether matching or not. – AlexGeorg Feb 11 '20 at 09:15
  • This doesn't address the question, but `if ((year > 2100 || year < 1) || (month > 12 || month < 1))` is just a confusing way of writing `if (year > 2100 || year < 1 || month > 12 || month < 1)`. Those internal parentheses don't change the meaning. Same for the rest of the `if` statements. It's only when you mix `&&` with `||` that you might need to use parentheses to override the builtin precedence rules. – Pete Becker Feb 11 '20 at 15:11

0 Answers0