今天做項目遇到這樣一個奇葩問題:我們先看如下代碼:
int ftcs = dealFtcs(ftcs); if(ftcs % 2 == 1){ //奇數 /* * 處理..... */ } else{ //偶數 /* * 處理...... */ }
/** * @desc 取余模擬算法 * @param dividend 被除數 * @param divisor 除數 * @return * @return int */ public static int remainder(int dividend,int divisor){ return dividend - dividend / divisor * divisor; }
看到這個我笑了,怪不得所有負數都往偶數處理那里跑。
當ftcs = -11時, -11 – (-11 / 2 * 2) = -1;
當ftcs = -10時, -10 – (-10 / 2 * 2) = 0;
……
所以對於上面的問題,非常簡單修正,改正如下:
int ftcs = dealFtcs(ftcs); if(ftcs % 2 == 0){ //偶數 /* * 處理..... */ } else{ //奇數 /* * 處理...... */ }
所以
1、對於判斷奇偶數,推薦用偶數判斷,不要用奇數判斷。
2、對於簡單的基礎知識,我們也不能忽略,做到知其然且知其所以然。