当我输入 1900 作为年份,2 作为月份时,我得到 29,而它应该是 28

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.

我明白 using namespace std 是一种不好的做法。但是,我的教授希望我们现在就这样学习。

我想我在二月份的循环中犯了一个错误,但我不知道它可能是什么。

#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;
}

你可以在网上找到闰年的计算方法。

如果我没记错的话是这样计算的

( year % 400 == 0 ) || ( year % 4 == 0 && year % 100 != 0 )

所以1900不是闰年,因为它可以被100整除但不能被400整除。

例如,二月的 if 语句可能如下所示

if (month == 2){

    cout << 28 + ( ( year % 400 == 0 ) || ( year % 4 == 0 && year % 100 != 0 ) )
         << " days" << endl;
}

问题出现在if(year%4)语句中。我猜你是想说 "when the year is divisible by 4, output 29 days".

但是,您的 if 语句实际上并没有这样做。

这个 if 语句首先计算 (year%4) 然后输出 29 天,如果它最终为真。在 C++ 中,表达式不等于 0 时为真。

因此,当 year%4 等于零时,year%4 的计算结果为真;这与您的实际意图完全相反。

要解决此问题,只需将您的 if 语句替换为 if(year%4 == 0)

编辑:闰年标准实际上要复杂得多;要使某年成为闰年,它必须可以被 400 整除 可以被 4 整除并且 而不是 100.

最后,if 语句应如下所示:

if(month == 2){
    if((year % 400 == 0) || (year%4 == 0 && year%100 != 0)){
        cout << "29 days" << endl;
    }
    else{
        cout << "28 days" << endl;
    }
}