如果我尝试编译这段代码...
fun main(args: Array<String>) {
for (i in 1.0..2.0) {
println(i)
}
}
...我收到错误消息
For-loop range must have an 'iterator()' method
如果我添加一个
step
...
fun main(args: Array<String>) {
for (i in 1.0..2.0 step .5) {
println(i)
}
}
...然后我收到一个新错误:
Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public infix fun CharProgression.step(step: Int): CharProgression defined in kotlin.ranges
public infix fun IntProgression.step(step: Int): IntProgression defined in kotlin.ranges
public infix fun LongProgression.step(step: Long): LongProgression defined in kotlin.ranges
public infix fun UIntProgression.step(step: Int): UIntProgression defined in kotlin.ranges
public infix fun ULongProgression.step(step: Long): ULongProgression defined in kotlin.ranges
那么我如何在一个范围内使用双精度呢? Kotlin 博客上的帖子 Ranges Reloaded 显示使用双范围是可以的。我不知道我的有什么问题。
从 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()
}
尽管如果您正在使用金钱,您可以这样做,但您实际上不应该使用
Double
(或Float
)。请参阅Java 实践 -> 代表金钱。
在某些情况下,您可以使用
repeat
循环。例如,在这种情况下,您可以计算循环将重复的次数。所以...
fun main() {
var startNum = 1.0
repeat(4) {
startNum += 0.5
//TODO something else
}
}
根据范围文档:
浮点数(
、Double
)没有定义其Float
运算符,而是使用标准库为泛型 Comparable 类型提供的运算符:rangeTo
public operator fun <T: Comparable<T>> T.rangeTo(that: T): ClosedRange<T>
该函数返回的范围不能用于迭代。
您将不得不使用其他类型的循环,因为您不能使用范围。
for(i in 0..2){ var j=i.toFloat()*0.5+1.0f 打印(一) }