【问题标题】:"(int)Math.ceil(double)" always return 1, even when the value is greater than 1"(int)Math.ceil(double)" 总是返回 1,即使值大于 1
【发布时间】:2015-07-28 22:23:42
【问题描述】:

我正在创建一个 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 使用

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

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

【问题讨论】:

    标签: java casting int double rounding


    【解决方案1】:

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

    因此难怪ceil 返回 1。

    【讨论】:

    • @TheDDestroyer12 注意负指数E-4
    • 抱歉,我才 14 岁,我们还没有在学校学习过指数。我以为这意味着别的东西。
    • 负指数表示数字小于 1。
    • @TheDDestroyer12 不要道歉,提问没有错。这是一个很好的习惯。
    【解决方案2】:

    请仔细查看您的输出,例如:

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

    并不意味着你有 7.02,而是 0.000702。最后有E-4。当您使用 ceil 时,它将始终返回 1。

    【讨论】:

      猜你喜欢
      • 2011-12-16
      • 2013-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 2019-10-10
      • 2014-04-13
      • 2017-03-20
      相关资源
      最近更新 更多