【问题标题】:Car Parking fee停车费
【发布时间】:2021-10-24 09:04:50
【问题描述】:

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

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

第 2 阶段 - 5 小时后,降至每小时 0.50 美元。如果汽车在公园内停留 6 小时,费用为 5.50 美元。

第 3 阶段 - 考虑到第 1 阶段和第 2 阶段,每天的费用为 14.50 美分。但是我们必须将每日费用固定为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)

    }

}

【问题讨论】:

    标签: kotlin fee


    【解决方案1】:

    您应该从大块开始,第 3 阶段。

    我更愿意避免将代码分支得比数学问题所需的更深。您可以将 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)
    }
    

    【讨论】:

      【解决方案2】:

      你应该从最严格的部分开始你的“如果”序列。

      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
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-11
        • 1970-01-01
        • 1970-01-01
        • 2019-09-25
        • 1970-01-01
        • 1970-01-01
        • 2015-11-27
        • 2011-11-25
        相关资源
        最近更新 更多