为什么运行不了?输入年月,知道改年该月的天数,(语言-c++)

img


为什么运行不了?输入年月,知道改年该月的天数,
为什么运行不了?题目为输入年月,知道改年该月的天数,
为什么运行不了?题目为输入年月,知道改年该月的天数,谢谢

运行不了的原因可能有很多,可能是代码有错误,也可能是编译环境出了问题。首先要根据具体的错误信息,检查代码中是否出现了拼写错误、语法问题或者逻辑错误等,以确定错误的原因。

如果代码没有问题,则可以尝试更换语言版本、编辑器或者编译器,看看是否可以解决运行不了的问题。

下面是一段C++代码,用于输入年月,知道改年该月的天数:

#include <iostream>
using namespace std;
 
int main() {
    int year, month;
    cout << "Please enter year and month: ";
    cin >> year >> month;
    
    int day = 0;
    switch (month) {
        case 1: case 3: case 5: case 7: case 8: case 10: case 12: 
            day = 31; break;  // 大月:31天 
        case 4: case 6: case 9: case 11: 
            day = 30; break;  // 小月:30天 
        case 2: 
            if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { // 闰年2月29天 
                day = 29; 
            } else {  // 平年2月28天 
                day = 28; 
            } 
        default: break;   // 默认情况下day为0  
    } 

    cout << year << "-" << month << ":" << day << endl;

    return 0; 
} 

如果回答有帮助,望采纳。

我为什么要输第3个数才运行?明明我程序上只有2个

方案来自 梦想橡皮擦 狂飙组基于 GPT 编写的 “程秘”


代码中有一个语法错误,需要在第5行最后一个分号后添加一个大括号来表示if语句块的范围,修正后的代码如下:

#include<iostream>
using namespace std;
int main()
{
    int year,month,day;
    cin>>year>>month;
    if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)
    {
        day=31;
    }
    else if(month==4||month==6||month==9||month==11)
    {
        day=30;
    }
    else if(month==2)
    {
        if((year%4==0&&year%100!=0)||year%400==0)
        {
            day=29;
        }
        else
        {
            day=28;
        }
    }
    else
    {
        cout<<"请输入正确的月份!"<<endl;
        return 0;
    }
    cout<<year<<"年"<<month<<"月有"<<day<<"天"<<endl;
    return 0;
}

此代码可以读入年月,根据月份和是否是闰年来确定该月的天数,并输出结果。注意,此代码没有对输入的年份和月份进行有效性检查,如果输入的年份或月份不在合法范围内,程序将输出错误提示信息。如果你需要对输入进行有效性检查,可以在读入年月后添加相应的判断代码。