Car Parking fee



我们的代码由3个阶段组成.

第1阶段-在停车场,最多5小时的费用为$ 1。

阶段2 - 5小时后,它下降到每小时0.50美元。如果汽车在停车场停留6小时,费用为5.50美元。

第三阶段-包括第一及第二阶段在内,每日收费为14.5仙。但是我们必须把每天的费用固定为15美元。如果汽车在停车场停留25小时,价格应该是15.50美元,而不是15美元。

我写了上面的第1和第2阶段,正如你在代码块中看到的。但是,我写不出每日费用,这是第三阶段

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)
}
}

你应该从第三阶段的大块开始。

对于数学问题,我更倾向于避免更深入的分支代码。您可以对单独的变量声明使用if/when,但是将所有的贡献者保存在一个单独的最终方程中,对没有贡献的变量使用0。我认为这使得代码更容易遵循,并且减少了重复。

余数运算符%对于这样的问题很有用。

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)
}

你应该开始写" if"按最严格部分排序。

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
}

最新更新