How to calculate time if we have the distance and speed (kilometers per hour) in Kotlin

1 Answer

0 votes
fun main() {
    // Initialize distance and speed
    val distance: Double = 30.0 // (in km)
    val speed: Double = 90.0    // (in km/h)

    // Check to avoid division by zero
    if (speed <= 0.0) {
        System.err.println("Speed must be greater than zero.")
        return 
    }

    // Calculate time
    val tm: Double = distance / speed
    println("Time required: %.2f hours".format(tm))

    // Optional: convert to hours and minutes
    val hours: Int = kotlin.math.floor(tm).toInt()
    val minutes: Int = kotlin.math.round((tm - hours) * 60).toInt()

    println("Which is approximately $hours hours and $minutes minutes.")
}



/*
run:

Time required: 0.33 hours
Which is approximately 0 hours and 20 minutes.

*/

 



answered Dec 6, 2025 by avibootz

Related questions

...