输入一个日期,输出这个日期中对应月份的最后一天/这个日期对应月份一共有几天

  • 输入:20200201

  • 输出:29


  • 输入:20190201

  • 输出:28


解题思路:

  • 根据年份判断是不是闰年,对2月份分别作出处理
  • 根据月份信息直接输出每个月对应的天数,这里可以使用switch选择语句

参考解答:

  • 使用string存储输入的日期
  • 通过获取子串的方式获取年份和月份信息
  • 为了便于计算,将获取的年份和月份信息转换为int型
#include <iostream>

using namespace std;

int main()
{
    string date;
    cin >> date;
    int year = stoi(date.substr(0,4));
    int flag = 0;  // 标记闰年
    int month = stoi(date.substr(4,2));  // 获取子串,并转换为int
    if(year % 4 == 0 && year % 100 == 0 && year % 400 ==0){ // 判断闰年
        flag = 1;
    }
    switch(month){
        case 1: cout << 31 << endl; break;  // 若写成'1',表示一个字符,实际上是使用ASCII表示的
        case 2:
            if(flag = 1){
                cout << 29 << endl;
            }
            else{
                cout << 28 << endl;
            }
            break;
        case 3:cout << 31 << endl;break;
        case 4:cout << 30 << endl;break;
        case 5:cout << 31 << endl;break;
        case 6:cout << 30 << endl;break;
        case 7:cout << 31 << endl;break;
        case 8:cout << 31 << endl;break;
        case 9:cout << 30 << endl;break;
        case 10:cout << 31 << endl;break;
        case 11:cout << 30 << endl;break;
        case 12:cout << 31 << endl;break;
        default:
            cout << "error!"<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/pinher/p/12611294.html