Search code examples
kotlincoin-change

Quarter counter (kotlin)


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.


Solution

  • 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")
    }
    
    fun changeWithDimes(x: Double) {
        var q = x.div(0.25).toInt() // Quarters
        var d = x.rem(0.25).div(0.10).toInt() // Dimes
        var rem = (x - (q * 0.25 + d * 0.10)).toFloat() // Remainder
        println(q) 
        println(d)
        println(rem)
    }