Ok, so first off I want to say that I am a newer programmer and I'm self taught. I'm currently trying to wrap my mind around how I would make a program (I'm using Kotlin) that would count the number of quarters out of a give value, and state the left over change.
so if I type input: 1.45
output will tell me:
5 quarters
0.20 Change
Now, I have done research on void methods, but I'm still confused on what that looks like. would anyone be willing to help me out on how id get started with this?
I mean like a quarter in terms of USD. So if you have $1.40 / $0.25 (quarter) = 5 Quarters and $0.20 left over. So I'm trying to make something that counts currency. I already have a weak code that calculates the math, but I need the number of quarters and left over change separated on 2 different lines of output.
CodePudding user response:
You can do println
to put each of the outputs on seperate lines
fun main() {
change(1.25)
changeWithNames(1.25)
}
fun change(x: Double) {
println(x.div(0.25).toInt()) // toInt to cut off the remainder
println(x.rem(0.25).toFloat()) // toFloat so that it rounds to the nearest hundreds place
}
fun changeWithNames(x: Double) {
println("${"%s".format(x.div(0.25).toInt())} quarters")
println("${"%.2f".format(x.rem(0.25))} Change")
}
CodePudding user response:
fun main() {
val input = "1.45"
// here you convert the input into minor units, e.g. $1.45 => 145 cents
val total = (input.toFloat() * 100).toInt()
// here you get whole number of quarters
val quartersCount = total / 25
// here you get the change and convert it back to major units (20 cents => $0.2)
val change = (total - 25 * quartersCount) / 100f
println("$quartersCount quarters")
println("${"%.2f".format(change)} Change") // bit more complex just to keep 2 decimal places
}