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

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实现)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章