一、截尾和舍取
對于float傳int,什么時候會舍棄小數,什么時候會將小數進位?
如何使用代碼,從而達到準確控制舍棄與進位呢?
答案:使用函數:Math.round(float f);
如下code:
public class HelloWorld {
? public static void main(String[] args) {
? ? System.out.println("My Logic keyBoard!");
? ? float above = 0.6f;
? ? float below = 0.4f;
? ? System.out.println("f2i above: "+(int)above+", below: "+(int)below);
? ? System.out.println("f2i Math.Rund above: "
? ? ? ? +Math.round(above)+", below: "+Math.round(below));
? }
}
輸出如下:
My Logic keyBoard!
f2i above: 0, below: 0
f2i Math.Rund above: 1, below: 0
總結:
從上面可以看出,float傳int會有精度的丟失;此外,小類型和大類型運算時,結果位大類型。