使用数据类型Double的Kotlin范围 [英] Ranges in Kotlin using data type Double

查看:419
本文介绍了使用数据类型Double的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)}")
    }

}

我收到错误消息,指出For循环范围必须具有"Iterator()"方法.它在本节(1.0..2.0中的i)中强调了我的双打.

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)

如何在范围内使用双打?重新加载范围的网站( 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<Double>不能用于迭代"(

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.

这篇关于使用数据类型Double的Kotlin范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆