单位转换公里到英里不会返回预期的结果

我试图把我的结果从公里转换成英里,但是我得到的结果是不正确的。

这里似乎是什么问题?

when { // TIME: To calculate your time, fill in your distance and pace time == null -> { val calculatedTime = distance!!.toLong() * timeToSeconds(pace.toString()) result.text = "The runner's time is ${secondsToTime(calculatedTime)}" } // DISTANCE: To calculate your distance, fill in your time and pace distance == null -> { val calculatedDistance = ((timeToSeconds(time).div(timeToSeconds (pace.toString()))) * 0.621371).format(2) result.text = "Distance is $calculatedDistance Miles" } // PACE: To calculate your pace, fill in your time and distance pace == null -> { // Calculate Pace val calculatedPace: Long = timeToSeconds(time).toLong() / distance.toLong() Log.i("PaceSeconds", calculatedPace.toString() + secondsToTime(calculatedPace)) result.text = "The runner's pace in miles is ${secondsToTime(calculatedPace)}" } } 

这是一个四舍五入的问题。 让我们分解它:

 val timeInSeconds = timeToSeconds(time) val paceInSeconds = timeToSeconds(pace) val timeDivPace = timeInSeconds.div(paceInSeconds) val calculatedDistance = timeDivPace * 0.621371 

使用评论中的示例数据, timeInSeconds是612, paceInSeconds是83.您希望timeDivPace是7.373494,但实际上是7,因为两个整数的除法返回一个整数作为结果。

修复很简单:将红利或除数转换为浮动,例如:

 val timeDivPace = timeInSeconds.div(paceInSeconds.toFloat())