日期计算

题目:日期计算
输入一个日期,输出这是这一年的第几天。(题目中没有给出闰年的定义)

输入 20131231
输出 365


题目分析:
该题目主要考察switch语句的使用和润年的判断;还需要注意的是输入的时候没有空格,需要由字符串输入转化日期(字符串转化为整型)输入。

参考代码如下:

#include <iostream>
#include <string> //别忘记
using namespace std;

int CalculatingDate(int year, int month, int day)
{
    int flag = 0;
    if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
        flag = 1;
    int cnt = 0;
    for(int i = 1;i < month; i++)
    {
        switch(i)   //由于是累加输入月份month之前的month-1个月份的天数(故i<month),所以没有case 12的情况。
        {
            case 1: 
            case 3:     
            case 5: 
            case 7: 
            case 8: 
            case 10: cnt += 31;break;
            case 2: cnt += 28 + flag;break;
            case 4: 
            case 6: 
            case 9: 
            case 11: cnt += 30;break;
        }
    }

    cnt += day;
    return cnt;
}

int main()
{
    string str;
    int year,month,day;
    cin >> str;
    year = (str[0] - '0') * 1000 + (str[1] -'0') * 100 + (str[2] - '0') * 10 + (str[3] - '0');
    month = (str[4] - '0') * 10 + str[5] - '0';
    day = (str[6] - '0') * 10 + str[7] - '0';
    cout << CalculatingDate(year,month,day) << endl;
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值