算法【计算某日是该年的第几天?】

Q: 输入日期,计算该日期是该年的第几天?

A:地球绕太阳运行周期为365天5小时48分46秒(合365.24219天)即一回归年(tropical year)。公历的平年只有365日,比回归年短约0.2422 日,所余下的时间约为每四年累计一天,故第四年于2月末加1天,使当年的历年长度为366日,这一年就为闰年。现行公历中每400年有97个闰年。按照每四年一个闰年计算,平均每年就要多算出0.0078天,这样经过四百年就会多算出大约3天来。因此每四百年中要减少三个闰年。所以公历规定:年份是整百数时,必须是400的倍数才是闰年;不是400的倍数的世纪年,即使是4的倍数也不是闰年。 原文介绍

#include<iostream>
#include<string>
#include<vector>

using namespace std;
//Is it a leap year? 
//1:如果年数可以整除400,则必定是闰年。
//2:如果年数不能整除100可以整除4 (刨除第25/50/75个闰年),则是闰年。
int leap(int a) {
    if ((a % 4 == 0 && a % 100 != 0) || a % 400 == 0) {
        return 1;
    } else {
        return 0;
    }
}

//计算输入的日期为该年的第几天
int number(int year, int m, int d) {
    int sum = 0, i, j, k;
    //存放平年每月的天数
    int a[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    //存放闰年每月的天数
    int b[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (leap(year))
        for (i = 0; i < m - 1; i++)
            sum += b[i];
    else
        for (i = 0; i < m - 1; i++)
            sum += a[i];
    sum += d;
    return sum;
}

int main() {
    int day = 0;
    string ymd = "";
    cin >> ymd;
    string year = ymd.substr(0, 4);
    string month = ymd.substr(4, 2);
    string days = ymd.substr(6, 2);
    //atoi():将字符串转换为整型值。
    day = number(atoi(year.c_str()), atoi(month.c_str()), atoi(days.c_str()));
    cout << ymd + " is the " << day << "th" << endl;
    return 0;
}

C语言itoa()函数和atoi()函数详解(整数转字符C实现)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值