使用数据类型Double的Kotlin范围

Nat*_*tts 8 double range kotlin

    fun calcInterest(amount: Double, interest: Double): Double {
    return(amount *(interest/100.0))
}

fun main(args: Array<String>) {

    for (i in 1.0..2.0 step .5) {
        println("&10,000 at 5% interest is = ${calcInterest(10000.0,i)}")
    }

}
Run Code Online (Sandbox Code Playgroud)

我得到错误说For循环范围必须有'Iterator()'方法.它强调了我在节中的双打(我在1.0..2.0)

我怎样才能在一个范围内使用双打?? Ranges Reloaded(https://blog.jetbrains.com/kotlin/2013/02/ranges-reloaded/)上的一个网站显示使用数据类型Double很好.我不知道我的错了.我需要使用双打,因为我的利率是使用小数.对编程完全陌生,所以希望有人可以简单解释.谢谢!

编辑:添加步骤.5

mfu*_*n26 11

从Kotlin 1.1开始,ClosedRange<Double>"不能用于迭代"(rangeTo()- 实用函数 - 范围 - Kotlin编程语言).

但是,您可以为此定义自己的step 扩展功能.例如:

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()
}
Run Code Online (Sandbox Code Playgroud)

虽然你可以这样做,但如果你正在使用钱,你不应该真正使用Double(或Float).请参阅Java实践 - >代表资金.


Tod*_*odd 3

根据范围的文档

浮点数 ( Double, Float) 没有定义其rangeTo运算符,而是使用标准库为泛型 Comparable 类型提供的运算符:

public operator fun <T: Comparable<T>> T.rangeTo(that: T): ClosedRange<T>
Run Code Online (Sandbox Code Playgroud)

该函数返回的范围不能用于迭代。

由于无法使用范围,因此您将不得不使用其他类型的循环。