"(int)Math.ceil(double)"总是返回1,即使值大于1。

3

我正在创建一款Android应用程序,需要计算设备的运动速度。我的方法是通过对之前几个位置的速度取平均值来实现。但是,我需要以km/h为单位并且使用int类型显示速度。

(int)Math.ceil(speedAsDouble)

然而,这始终等于1,即使speedAsDouble7.88252460.58178
以下是相关代码:

// 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 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

我花了很多时间研究这个问题,尝试使用不同的变量类型和强制类型转换,但是没有成功。

2个回答

4
在你打印的所有输出中(除了第一个为0),Speed 都小于1(例如7.026718463748694E-45.27003884781152E-4等等...)。请注意负指数。

因此,ceil 返回1也就不奇怪了。

@TheDDestroyer12 注意负指数 E-4 - Eran
抱歉,我只有14岁,我们还没有在学校学习指数。我以为它意味着其他的东西。 - Daniel Kvist
负指数意味着该数字小于1。 - Carcigenicate
@TheDDestroyer12 不要道歉,提问并没有错。这是一个非常好的习惯。 - Tomek

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。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接