int accel = (int)Math.abs(randomAccel);
該行執行3個步驟
- 獲取的
randomAccel
- 絕對值的值強制轉換爲
int
(浮點數被截斷)
- 指定
int
的值爲accel
現在讓我們來看看當輸入在[-9.4182062E-9,9.593071E- 8]
範圍內時會發生什麼(順便說一下-5.485747E-5
不在這個範圍內。)
Input value -9.4E-9 = -0.0000000094
1. -9.4E-9 converted to 9.4E-9
2. 9.4E-9 cast to int, fractional part is removed. Value is 0
3. 0 is assigned to `accel`
如果你只是想最顯著的數字,你可以通過10^8
繁殖,並看看是否值大於0
更大,如果是則trucate,否則乘以10再截斷:
int accel = 0;
r = Math.abs(randomAccel) * 100000000;
if(r >= 10) {/* error out of range */}
else if(r > 0) accel = (int)r;
else
{
r *= 10;
accel = (int)r;
}
http://stackoverflow.com/q/1295424/2282538 – Tyler