Kotlin 中使用数据类型 Double 的范围 [英] Ranges in Kotlin using data type Double
问题描述
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)}")
}
}
我收到错误消息说 For 循环范围必须有一个 'Iterator()' 方法.它强调了我在该部分中的双打(我在 1.0..2.0 中)
I get the error saying the For-loop range must have an 'Iterator()'Method. It underlines my doubles in the section (i in 1.0..2.0)
如何在一个范围内使用双精度数?Ranges Reloaded 网站 (https://blog.jetbrains.com/kotlin/2013/02/ranges-reloaded/ )表明使用数据类型 Double 很好.我不知道我的有什么问题.我需要使用双打,因为我的利率使用小数.对编程完全陌生,所以希望有人能简单地解释一下.谢谢!
How can I use doubles in a range?? A website on Ranges Reloaded (https://blog.jetbrains.com/kotlin/2013/02/ranges-reloaded/ ) shows that using datatype Double is fine. I don't know what's wrong with mine. I need to use doubles for the fact that my interest rates are using decimals. Completely new to programming so hopefully someone can explain simply. Thanks!
添加步骤 .5
推荐答案
从 Kotlin 1.1 开始,ClosedRange
不能用于迭代"(rangeTo()
- 实用函数 - Ranges - Kotlin 编程语言).
As of Kotlin 1.1, a ClosedRange<Double>
"cannot be used for iteration" (rangeTo()
- Utility functions - Ranges - Kotlin Programming Language).
但是,您可以定义自己的 step
扩展功能.例如:
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()
}
虽然您可以在使用金钱的情况下执行此操作,但您实际上不应该使用 Double
(或 Float
).请参阅 Java 实践 -> 代表金钱.
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.
这篇关于Kotlin 中使用数据类型 Double 的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!