Ranges in Kotlin using data type Double

后端 未结 3 999
無奈伤痛
無奈伤痛 2020-12-20 12:21
    fun calcInterest(amount: Double, interest: Double): Double {
    return(amount *(interest/100.0))
}

fun main(args: Array) {

    for (i in 1.0..2.         


        
相关标签:
3条回答
  • 2020-12-20 12:35

    As of Kotlin 1.1, a ClosedRange<Double> "cannot be used for iteration" (rangeTo() - Utility functions - Ranges - Kotlin Programming Language).

    You can, however, define your own step extension function for this. e.g.:

    infix fun ClosedRange<Double>.step(step: Double): Iterable<Double> {
        require(start.isFinite())
        require(endInclusive.isFinite())
        require(step > 0.0) { "Step must be positive, was: $step." }
        val sequence = generateSequence(start) { previous ->
            if (previous == Double.POSITIVE_INFINITY) return@generateSequence null
            val next = previous + step
            if (next > endInclusive) null else next
        }
        return sequence.asIterable()
    }
    

    Although you can do this if you are working with money you shouldn't really be using Double (or Float). See Java Practices -> Representing money.

    0 讨论(0)
  • 2020-12-20 12:40

    According to the documentation for ranges:

    Floating point numbers (Double, Float) do not define their rangeTo operator, and the one provided by the standard library for generic Comparable types is used instead:

    public operator fun <T: Comparable<T>> T.rangeTo(that: T): ClosedRange<T>
    

    The range returned by this function cannot be used for iteration.

    You will have to use some other kind of loop since you can't use ranges.

    0 讨论(0)
  • 2020-12-20 12:54

    In some cases you can use repeat loop. For example in this situation you can count how many time this the loop will repeat. so...

    fun main() {
        var startNum = 1.0
        repeat(4) {
            startNum += 0.5
            //TODO something else
        }
    }
    
    0 讨论(0)
提交回复
热议问题