Home > front end >  Car Parking fee
Car Parking fee

Time:10-25

Our code consists of 3 stages.

Stage 1 - In the car park, up to 5 hours fee is $ 1.

Stage 2 - After 5 hours, it drops to $ 0.50 per hour. If the car stays in the park for 6 hours, the fee is $ 5.50.

Stage 3 - the fee per day, taking into account the 1st and 2nd stages, is 14.50 cents. But we have to make the daily fee fixed as $ 15. If the car stays in the park for 25 hours, the price should be 15.50, not $ 15.

I wrote stages 1 and 2 above, as you can see in the code block. However, I could not write the daily fee, which is the 3rd stage.

fun main(args: Array<String>) {
  
    var hours = readLine()!!.toInt()
    var total: Double = 0.0
    var price = 0.0
    if (hours <= 5) {
        price= 1.0
        total = hours * price
        println(total)

    } else if (hours>=6) {
        price= 0.5
        total=hours*price-2.5 5.0
        println(total)

    }

}

CodePudding user response:

You should start you "if" sequence by the most restrictive part.

total = 0
if (hours >= 24) {
    // number of days
    days = int(hours / 24)
    price = 15
    total = days * price
    // excess of hours rated at 0.5 / hour
    hours = hours % 24
    price = 0.5
    total  = hours * price
} else if hours >= 6 {
    price = 0.5
    total = (hours - 5) * price   1
} else {
    // 5 or less hours
    total = 1
}

CodePudding user response:

You should start with the big chunk, stage 3.

I prefer to avoid branching code deeper than necessary for math problems. You can use if/when for individual variable declarations, but keep all contributors in a single final equation, using 0 for variables that won't contribute. I think this makes code easier to follow and less repetitive.

The remainder operator % is useful for problems like this.

fun main() {
    val totalHours = readLine()!!.toInt()

    val days = totalHours / 24 // Number of complete days charged at daily rate
    val hours = totalHours % 24 // The remainder is hours charged at hourly rate

    // Hours up to five cost an additional 0.5 of hourly rate
    val higherRateHours = when {
        days > 0 -> 0 // Don't charge the high hourly rate because already covered within first day
        else -> totalHours.coerceAtMost(5)
    }

    val total = days * 15.0   hours * 0.5   higherRateHours * 0.5
    println(total)
}
  • Related