算法【計算某日是該年的第幾天?】

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實現)

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