干支法纪年算法

时间:2021-05-06 09:42:52

在我国古代和近代,一直采用干支法纪年。它采用10天干和12地支配合,一个循环周期为60年。

10天干是:甲,乙,丙,丁,戊,己,庚,辛,壬,癸
12地支是:子,丑,寅,卯,辰,巳,午,未,申,酉,戌,亥

如果某年是甲子,下一年就是乙丑,再下是丙寅,......癸酉,甲戌,乙亥,丙子,....

总之天干、地址都是循环使用,两两配对。

今年(2012)是壬辰年,1911年辛亥革命
已知最近的甲子年是1984年。
#include<stdio.h>
void f(int year)
{
    char* x[] = {"甲","乙","丙","丁","戊","己","庚","辛","壬","癸"};
    char* y[] = {"子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"};

    int n = year - 1984;

    while(n<0) n += 60;

    printf("%s%s\n", x[n%10], y[n%12]);
}

int main(int argc, char* argv[])
{
    f(1911);
    f(1970);
    f(2012);
    return 0;
}