0

i dont understand why the output is diffrent

so i was working on the Kotlin parking fee code challenge at the end of control flow and i am not understanding why calculateFee outputs correct number but the calculateFeeSecond outputs wrong number can someone please help me understand Thanks here is the code below fun calculateFee() { var hours = readLine()!!.toInt() var total: Double = 0.0 if(hours <= 5) { total = hours * 1.0 } else if(hours > 5 && hours < 24) { total = 5 + ((hours - 5) * 0.5) } else if(hours > 24) { total = 15 * (hours / 24) + 0.5 * (hours % 24) } println(total) } fun calculateFeeSecond() { var hours = readLine()!!.toInt() var total: Double = 0.0 if(hours in 1..100) { if(hours == 5) { total = hours.toDouble() * 1 } else if(hours > 5 && hours < 24) { total = 5 + ((hours.toDouble() - 5) * .5) } else { total = (hours / 24 * 15) + (0.5 * hours % 24) } } println(total)

1st Apr 2021, 3:54 AM
Christopher Scott Adams
Christopher Scott Adams - avatar
2 Réponses
+ 3
Your second if statement should be hours <= 5 not hours ==5 You need to use '%' operator before '*' because both operators have same precedence. So, they are evaluated from left to right total = (hours / 24 * 15) + ( hours % 24 * 0.5)
1st Apr 2021, 4:48 AM
Simba
Simba - avatar
+ 1
Thank you very much! Im sorry if that was a dumb question i wasnt thinking about the order of operations
1st Apr 2021, 5:57 AM
Christopher Scott Adams
Christopher Scott Adams - avatar