書上的例子:數組
寫一個計算醫療保險費率的程序,費率跟年齡、性別、婚姻情況以及吸菸與否有關。第一反應可能就是一大堆的if-else語句,以下:網絡
#define FEMALE 1 #define MALE 0 #define MARRIED 1 #define UNMARRIED 0 #define SMOKING 1 #define NOSMOKING 0 if(gender ==FEMALE ) { if(maritalStatus ==MARRIED ) { if(smokingStatus ==SMOKING ) { if(age<18){rate=250;} else if(age==18){rate=300}; else if(age==19){rate=350}; ... else if(age>65){rate=500} } else {...} } } else...
天啊,是否是一大堆的if-else,感受快搞暈的節奏,函數
即便第一回寫的時候還沒暈,估計下一次來看的時候,直接傻掉,blog
若是這裏邏輯出了什麼問題,還一邊大罵傻屌~~~it
因此今天引出咱們的主角-表驅動法,所謂表驅動法是什麼,你們參考百度或者代碼大全~~class
其實爲了讓下次看懂,並且利於維護,通常來講咱們就想一個函數實現就能夠了,百度
就像float
GetRate(female,unmarried,nosmoking,age_21);
因此下面咱們來實現吧,丟掉那些討厭的if-else:程序
數據部分:即保險的費率文件讀取
影響保險費率除了年齡因素外還有3個因素,而年齡因素是主因素,因此咱們能夠定義把每一個年齡的費率存在一個獨立的數組裏面,
可是因爲還有3個因素,因此咱們須要以下幾個數組:
enum { MALE_UNMARRIED_NOSMOKING =0, MALE_UNMARRIED_SMOKING, MALE_MARRIED_NOSMOKING, MALE_MARRIED_SMOKING, FEMALE_UNMARRIED_NOSMOKING, FEMALE_UNMARRIED_SMOKING, FEMALE_MARRIED_NOSMOKING, FEMALE_MARRIED_SMOKING, MAX_RATE_NUMBER }; typedef float male_unmarried_nosmongking,male_married_nosmongking; typedef float male_unmarried_smongking,male_married_smongking; typedef float female_unmarried_nosmongking,female_married_nosmongking; typedef float female_unmarried_smongking,female_married_smongking; //數據,能夠從文件讀取,或者網絡等等,這裏爲了方便隨便賦值 male_unmarried_nosmongking MUN[48] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,}; male_unmarried_smongking MUS[48] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,}; male_married_nosmongking MMN[48] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,}; male_married_smongking MMS[48] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,}; female_unmarried_nosmongking FUN[48] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,}; female_unmarried_smongking FUS[48] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,}; female_married_nosmongking FMN[48] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,}; female_married_smongking FMS[48] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,};
好,這下有了8個數組來存儲咱們的數據,但是總感受仍是不方便,因此再來封裝下:
typedef struct { float* rate; }Rate; Rate RateTable[MAX_RATE_NUMBER] = {(float*)MUN, (float*)MUS, (float*)MMN, (float*)MMS, (float*)FUN, (float*)FUS, (float*)FMN, (float*)FMS };
這些看上去清爽多了吧~~
終於到了主函數實現的時候了,
int GetRate(int gender,int maritalStatus,int smokingStatus,int age) { //1,年齡因素,爲了利於在數組中快速找到對應的費率,須要利用數組自然的下標優點, //<17的費率,數組下標0;18數組下標1;...大於65數組下標爲65-17 //是否是又看到了討厭的IF-ELSE,不過不要緊,這裏先無論它,畢竟判斷少,你們都看得懂 int ageFactor = 0; if (age<18) { ageFactor = 0; } else if (age>65) { ageFactor = 65-17; } else { ageFactor = age-17; } //2,其餘因素 //注意到在RateTable數組中存儲是有規律的,因此咱們的其餘因素也利用數組的自然因素。。。。 int otherFacotors = gender*4+maritalStatus*2+smokingStatus;//0,1,2,3,4,5,6,7,8 //高潮來了哦,不要覺得是一大堆的if-else語句哦。。。 //其實就一句話~~ return RateTable[otherFacotors].rate[ageFactor]; //是否是很牛逼的樣子~~ }
若是你看到這裏,恭喜你,內功又深刻了一成~~
代碼大全說,其實程序的控制邏輯人是不擅長的,可是咱們擅長數據,
因此咱們就盡情的利用表驅動法,把邏輯放入數據中吧~~~