如何计算科特林的立方根?

时间:2019-04-02 17:00:13

标签: kotlin

在Kotlin中有一个内部的数学库,我只找到平方根,但没有立方根。

cubic root

import kotlin.math.sqrt
import kotlin.math.pow

fun Formule(a:Int):Double{
    //no working
    //rs = a.pow(1/3)
    //function
    retun rs
}

fun main(args: Array<String>){
    val calc = Formule(9)
}

3 个答案:

答案 0 :(得分:2)

如果您不需要Kotlin多平台支持,则Java标准库具有Math.cbrt(),可以从Kotlin安全地调用它。

<img(?!.*\s+alt\s*=).+$

答案 1 :(得分:1)

无需使用 Java库,只需使用 Kotlin 之一:

import kotlin.math.pow

fun formula(a:Int):Double {
    return a.toDouble().pow(1/3.toDouble())
}

只需测试一下:

println(formula(9)) //2.080083823051904

println(formula(27)) //3.0

答案 2 :(得分:0)

    /**
     * Program: Kotlin program to calculate the cube root of 125
     * Date: Tue, 6-4-2021
     * @author: ANKUR SAXENA
     * Platform: Windows 10 Pro/x64/Kotlin v1.4.31/VS Code
     */

    // cube root logic, var result = (Math.cbrt(num))

    // program start
    // main function
    fun main (args: Array)
    {
        // declare variables
        var num: Int = 125

        // print value
        println ("Value of the number: $num\n")

        // calculate cube root
        var cubeRoot: Double = (Math.cbrt(num.toDouble()))

        // print cube root
        println ("\nCube root of $num is: $cubeRoot\n")
    }

// program end

// 将此文件保存为 'CubeRoot1.kt'
// 编译:$ kotlinc CubeRoot1.kt [按回车]
// 执行:$ kotlin CubeRoot1Kt [按回车]

输出:

    Value of the number: 125


    Cube root of 125 is: 5.0
相关问题