繁体   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