C++ 当我输入1900表示年份,2表示月份时,我得到29,而它应该是28

C++ 当我输入1900表示年份,2表示月份时,我得到29,而它应该是28,c++,loops,if-statement,leap-year,C++,Loops,If Statement,Leap Year,编写一个程序month.cpp,要求用户输入年份和月份(1-12),并打印该月份的天数(考虑闰年)。即使您知道这些语言结构,也不能使用开关大小写或数组 我理解使用命名空间std是一种不好的做法。然而,我的教授希望我们现在就这样学习 我想我在二月的循环中犯了一个错误,但我不知道它可能是什么 #include <iostream> using namespace std; int main(){ int year = 0; int month = 0; cou

编写一个程序month.cpp,要求用户输入年份和月份(1-12),并打印该月份的天数(考虑闰年)。即使您知道这些语言结构,也不能使用开关大小写或数组

我理解
使用命名空间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;
}
#包括
使用名称空间std;
int main(){
整年=0;
整月=0;
年份;
月份;

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

如果我没有弄错的话,那么它的计算方法如下

( year % 400 == 0 ) || ( year % 4 == 0 && year % 100 != 0 )
因此
1900
不是闰年,因为它可以被
100
整除,但不能被
400
整除

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

if (month == 2){

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

cout问题出现在
if(年份%4)
语句中。我猜您的意思是“当年份可被4整除时,输出29天”

但是,if语句实际上并没有做到这一点

此if语句首先计算<代码>(年% 4)< /C> >如果输出为真,则输出29天。在C++中,当不等于0时,表达式为真。 因此,当

year%4
不等于零时,
year%4
的计算结果为true;这与您实际打算做的正好相反

要解决此问题,只需将if语句替换为
if(年份%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;
    }
}
if(月==2){
如果((第%400年==0)| |(第%4年==0和第%100年!=0)){

cout比
年份%4==0
更复杂,
%100==0
也有例外,
%400==0
如果(年份%4)
应该是
如果(年份%4==0)
。或多或少。1900年不是闰年吗?也就是说29年是正确的?哦,我现在明白我的错误了。我应该查一下它是如何计算出来的,这是个可怕的错误。谢谢你的帮助!