簡體   English   中英

“(int)Math.ceil(double)”總是返回1,即使該值大於1

[英]“(int)Math.ceil(double)” always return 1, even when the value is greater than 1

我正在創建一個Android應用程序,我需要計算設備的移動速度。 我通過平均一些早期位置的速度來做到這一點。
不過,我需要的速度在km/hint ,所以我用

(int)Math.ceil(speedAsDouble)

但是,即使speedAsDouble7.88252460.58178 ,它總是等於1
這是代碼的相關部分:

// Create a variable for the speed
double speedAsDouble = 0d;

// Loop through the last points
for(int i = 0; i < lastPoints.size() - 1; i++)
{
    // Add the speed for the current point to the total speed
    speedAsDouble += (double)(lastPoints.get(i).distanceTo(lastPoints.get(i + 1)) / (lastPoints.get(i + 1).getTime() - lastPoints.get(i).getTime()));
}

// Divide the speed by the number of points
speedAsDouble /= (double)lastPoints.size();
// Convert the speed to km/h
speedAsDouble *= 3.6d;

// Log the speed
System.out.println("Speed: " + speedAsDouble);

然后,我將數字四舍五入,並使用如上所述將其轉換為int

int speedAsInt = (int)Math.ceil(speedAsDouble)

然后再次記錄該號碼

System.out.println("Rounded speed: " + speedAsInt)

這是日志的一部分:

05-17 12:00:42.605  24610-24610/package I/System.out﹕ Speed: 0.0
05-17 12:00:42.635  24610-24610/package I/System.out﹕ Rounded speed: 0
05-17 12:00:43.625  24610-24610/package I/System.out﹕ Speed: 7.026718463748694E-4
05-17 12:00:43.645  24610-24610/package I/System.out﹕ Rounded speed: 1
05-17 12:00:44.595  24610-24610/package I/System.out﹕ Speed: 5.27003884781152E-4
05-17 12:00:44.615  24610-24610/package I/System.out﹕ Rounded speed: 1
05-17 12:00:45.595  24610-24610/package I/System.out﹕ Speed: 4.216031078249216E-4
05-17 12:00:45.635  24610-24610/package I/System.out﹕ Rounded speed: 1
05-17 12:00:46.595  24610-24610/package I/System.out﹕ Speed: 0.002668234216980636
05-17 12:00:46.605  24610-24610/package I/System.out﹕ Rounded speed: 1

我花了很多時間看這個,嘗試不同的變量類型和鑄造變量,但沒有成功。

在您打印的所有輸出中(除了第一個輸出為0) Speed小於1( 7.026718463748694E-4 5.27003884781152E-4等...)。 注意負指數。

因此,毫無疑問, ceil返回1。

請仔細查看輸出,例如:

05-17 12:00:43.625 24610-24610/package I/System.out﹕ Speed: 7.026718463748694E-4

並不意味着你有7.02,但0.000702。 最后有E-4 當你使用ceil時,它總會返回1。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM