1
此代码参考网上代码编写,做了删减,做了程序优化。
一百年太久,只争朝夕,所以农历数据只取了30年。
如下这段代码,在LunarCalendar函数的while循环中,每次执行while(Sun_NY>=StaticDayCount)这个循环判断条件,则Spring_NY这个unsigned int变量会变成0,执行循环中的if((LunarCalendarTable[year-2001]&(0x080000>>(index-1)))==0)条件判断,则Sun_NY会等于StaticDayCount的值(29或者30),虽然在这里Spring_NY的改变已经不会影响函数执行结果的正确,但这个错误让我感觉莫名其妙啊。有兴趣的可以COPY代码用keil编译后单步执行,查看local窗口中的变量值。另外,如果把Spring_NY和Sun_NY的类型改为unsigned long则不会出现这个问题。也查看了这些变量在data区的地址,没有发现重叠现象。关于农历数据的说明见下面,这些数据是网上直接COPY过来的,未做正确性检查,抽验了几个是正确的。完整原代码如下
#include
#define uchar unsigned char
#define uint unsigned int
#define ulong unsigned long
uint LunarYear;
uchar LunarMonth;
uchar LunarDay;
ulong code LunarCalendarTable[] = {
0x4D4AB8,0x0D4A4C,0x0DA541,0x25AAB6,0x056A49,0x7AADBD,0x025D52,0x092D47,0x5C95BA,0x0A954E,/*2001-2010*/
0x0B4A43,0x4B5537,0x0AD54A,0x955ABF,0x04BA53,0x0A5B48,0x652BBC,0x052B50,0x0A9345,0x474AB9,/*2011-2020*/
0x06AA4C,0x0AD541,0x24DAB6,0x04B64A,0x69573D,0x0A4E51,0x0D2646,0x5E933A,0x0D534D,0x05AA43/*2021-2030*/
}; uint MonthAdd[12] = {0,31,59,90,120,151,181,212,243,273,304,334};void LunarCalendar(uint year,uchar month,uchar day1)
{
uint Spring_NY=0,Sun_NY=0; //Spring_NY 记录春节离当年元旦的天数。Sun_NY 记录阳历日离当年元旦的天数。
uchar StaticDayCount=0,index=0,flag=0;//StaticDayCount记录大小月的天数 29 或30 index 记录从哪个月开始来计算,
//flag 是用来对闰月的特殊处理。
if(year<2002||year>2030)
goto end;
Spring_NY=(((LunarCalendarTable[year-2001]&0x60)>>5)-1)*31+(LunarCalendarTable[year-2001]&0x1F)-1;//取得当年春节到元旦的天数
Sun_NY=MonthAdd[month-1]+day1-1; //取查询日期距元旦的天数
if((!(year%4))&&(month>2)) //闰年且月份大于2则加1天
{
Sun_NY++;
}
if(Sun_NY
{
year--;
Spring_NY =(((LunarCalendarTable[year-2001]&0x60)>>5)-1)*31+(LunarCalendarTable[year-2001]&0x1F)-1;
Sun_NY+=365;
if(!(year%4))
{
Sun_NY++;
}
} Sun_NY-=Spring_NY; //取得查询日期到正月初一的天数
while(Sun_NY>=StaticDayCount)
{
Sun_NY-=StaticDayCount;
index++;
if((LunarCalendarTable[year-2001]&(0x080000>>(index-1)))==0)
StaticDayCount=29;
else
StaticDayCount=30;
}
flag=(LunarCalendarTable[year-2001]&0xf00000)>>20; //取得闰月信息
if(flag!=0)
{
if(index>flag)
index--;
}
LunarYear=year;LunarMonth=index;LunarDay=Sun_NY+1;
end:;
}void main()
{
LunarCalendar(2012,1,14);
LunarCalendar(2012,6,6);
while(1);
}
|
|