dimanche 14 juin 2020

When I input 1900 for the year and 2 for the month I get 29 when it should be 28

Write a program month.cpp that asks the user to input the year and the month (1-12) and prints the number of days in that month (taking into account leap years). You may not use switch case or arrays even if you know these language constructs.

I understand using namespace std is a bad practice. However, my professor wants us to learn like this as of now.

I think I am making a mistake with my loop for February, but I don't know what it might be.

#include <iostream>

using namespace std;

int main(){
    int year = 0;
    int month = 0;
    cout << "Enter year: ";
    cin >> year;
    cout << endl;
    cout << "Enter Month: ";
    cin >> month;
    cout << endl;


    if (month == 1){
        cout << "31 days" << endl;
    }
    if (month == 2){
        if (year % 4){
            cout << "29 days" << endl;
        }
        else{
            cout << "28 days" << endl;

        }
    }    

    if (month == 3){
        cout << "31 days" << endl;
        }
    if (month == 4){
        cout << "30 days" << endl;

    }
    if (month == 5){
        cout << "31 days" << endl;
    }
    if (month == 6) {
        cout << "30 days" << endl;
    }
    if (month == 7){
        cout << "31 days" << endl;
        }
    if (month == 8){
        cout << "31 days" << endl;

    }
    if (month == 9){
        cout << "30 days" << endl;
    }
    if (month == 10) {
        cout << "31 days" << endl;
    }
    if (month == 11){
        cout << "30 days" << endl;
    }
    if (month == 12) {
        cout << "31 days" << endl;
    }

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire