Need Help Please

I am new to C++ and I am trying to figure out why the program will not get the number of days in a leap year correct. Any help is appreciated!

#include <iostream>
using namespace std;

int main()
{

int month,year,day;
cout << "Enter a month and a year: ";
cin >> month >> year;
if (month > 12)
{
cout << "error in month" << endl; exit(1);
}
if (year % 4 == 0)

day = 29;
else
day = 28;

if (month == 4 || month == 6 || month == 9 || month == 11)
day = 30;
else
day = 31;

cout << "The number of days in " << month <<" month is: "<< day << endl << endl;

return 0;
}
You set day to 28/29, regardless of whether it's February or not.
And then you overwrite day with either 30 or 31.
How could i change it to not overwrite the code in front?
By moving the code in front to the back and inside the block of an appropriate if statement.
Could you show me how to write that in code? I not sure what you mean by that.
You'd want something like:
1
2
3
4
5
6
if(month == 2) {
    if(year%4 == 0) day = 29;
    else day = 28;
}
else if (month == 4 || month == 6 || month == 9 || month == 11)  day = 30;
else day = 31;



The problem with your code at the minute is you're not actually checking whether the month is february.

Its also possible (as stated above) to trigger both your if statements which you wouldn't want to do. In my code only one of the 5 if, else if or else statements can ever be triggered.

Hope this helped.
Last edited on
year%4==0 is not the correct definition of leap year.
it is : year%4==0 && year%100!=0 || year%400==0;
Topic archived. No new replies allowed.