公司須要解決判斷當前日期處於那個對應節氣區間,參照需求算法
在當前網上關於而是二十四節氣的算法核心:spa
if(iDay <15) day= 15 - ((flag>>4)&0x0f); else day = ((flag)&0x0f)+15; int index = -1; //對應日期節氣判斷 if(iDay == day){ index = (iMonth-1) *2 + (iDay>15? 1: 0); }
修改後代碼改正以下,能夠判斷出對應節氣區間區間:code
1 - (NSInteger)lunarIndex { 2 NSCalendar *localeCalendar = [NSCalendar currentCalendar]; 3 4 unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; 5 6 NSDateComponents *localeComp = [localeCalendar components:unitFlags fromDate:self]; 7 8 NSInteger iYear = localeComp.year; 9 NSInteger iMonth = localeComp.month; 10 NSInteger iDay = localeComp.day; 11 12 13 int array_index = (iYear - START_YEAR)*12+iMonth -1 ; 14 15 int64_t flag = gLunarHolDay[array_index]; 16 int64_t day; 17 18 int index_in_month = 0; 19 20 if(iDay <15) 21 day= 15 - ((flag>>4)&0x0f); 22 else { 23 day = ((flag)&0x0f)+15; 24 index_in_month += 1; 25 } 26 27 int index = -1; 28 29 index = (iMonth-1) *2 + index_in_month; 30 31 if (iDay >= day) { 32 33 } else { 34 index -=1; 35 if (index < 0) { 36 index = 24 - 1; 37 } 38 } 39 //從立春開始 40 if ( index >= 0 && index < 24 ) { 41 return (index + 22) % 24 + 1; 42 } else { 43 return InvalidLunarIndex; 44 } 45 }
在改寫過程當中出現了邊界值未判斷的問題,更正後,將全部相關條件結果在同一判斷條件內完成組織,幹掉三元。component
如此看,爲了不邊界值問題,應該將相關條件結果在同一判斷條件內統和,而後世界就和諧了。blog