public static boolean isOdd(int i){java
return i % 2 == 1;編程
}編程語言
上面的方法真的能找到全部的奇數麼?優化
A:沒有考慮到負數問題,若是i爲負則不正確。應該return i%2 == 0ci
2. 浮點數相減io
System.out.println(2.0-1.9);for循環
A:Java中的簡單浮點數類型float和double不可以進行運算。不光是Java,在其它不少編程語言中也有這樣的問題。在大多數狀況下,計算的結果是準確的,可是多試幾回(能夠作一個循環)就能夠試出相似上面的錯誤。固然加減乘除都有可能有問題,好比:編譯
System.out.println(0.05+0.01);循環
System.out.println(1.0-0.42);二進制
System.out.println(4.015*100);
System.out.println(123.3/100);
這是由於有些十進制有限位數的小數,到二進制裏面可能會變成無限循環小數,在浮點數中不能表示而損傷精度。
解決方法:
2.1. 若是是判斷a-b是否等於c,或者a+b是否等於c的,可使用
if(0.05+0.01-0.06 < 0.0000001)
{
}
2.2. 在《Effective Java》這本書中提到一個原則,float和double只能用來作科學計算或者是工程計算,在商業計算中咱們要用 java.math.BigDecimal來解決
System.out.println((new BigDecimal("2.0")).subtract(new BigDecimal("1.9")).doubleValue());
3. 無限循環
public static final int END = Integer.MAX_VALUE;
public static final int START = END - 2;
public static void main(String[] args) {
int count = 0;
for (int i = START; i <= END; i++)
count++;
System.out.println(count);
}
A:這裏無限循環的緣由就是當i爲Integer.MAX_VALUE時,此時for循環是先++,而後判斷i是否<=END,當i爲Integer.MAX_VALUE再++時,i變成了負數。因此就一直循環下去。
變成負數的緣由就是int溢出了。這裏將<=END改爲<END就能夠解決問題。
4. 到底返回什麼?
public static boolean decision() {
try {
return true;
} finally {
return false;
}
}
A:返回false。此時return true是不可達語句,在編譯階段將優化去掉。