什么是Kotlin中的指数运算符.我认为它会,**
但它似乎在我的代码中引发错误.
when (pendingOperation) {
"=" -> operand1 = value
"÷" -> operand1 = if (value == 0.0) {
Double.NaN // handle attempt to divide by zero
} else {
operand1!! / value
}
"x" -> operand1 = operand1!! * value
"?" -> operand1 = operand1!! - value
"+" -> operand1 = operand1!! + value
"a^b" -> operand1 = operand1!! ** value
Run Code Online (Sandbox Code Playgroud)
Zoe*_*Zoe 20
与Java一样,Kotlin没有指数运算符.Java也Math.pow
可以和Kotlin一起使用,但是Kotlin也有Float和Double的扩展功能,你可以使用它.
如果你需要使用带有Ints或Longs的指数,你只需转换为double,然后再转换为int/long.或者,您可以创建自己的方法.
它非常直接.因为它是一个扩展功能; 只需要调用.pow
一个Double
或一个Float
对象:
"a^b" -> operand1 = operand1!!/*.toDouble()*/.pow(value)/*.toInt()*/
//Not sure what type operand1 is, so the comments are there if it's not a double or float, and the second assumes it's an int
Run Code Online (Sandbox Code Playgroud)
但是,你可以创建一些``
ctions来获得一个:
/**
* Integer power using [Double.pow]
*/
infix fun Int.`**`(exponent: Int): Int = toDouble().pow(exponent).toInt()
/**
* Long power using [Double.pow]
*/
infix fun Long.`**`(exponent: Int): Long = toDouble().pow(exponent).toLong()
/**
* Double power using [Double.pow]
*/
infix fun Float.`**`(exponent: Int) : Float = this.pow(exponent)
/**
* Float power using [Float.pow]
*/
infix fun Double.`**`(exponent: Int) : Double = this.pow(exponent)
Run Code Online (Sandbox Code Playgroud)
有两个注释函数可以使用手动计算而不是Double.pow来替代Long和Integer power.
哪个允许你打电话:
val x = 10
val exponent = 2
println(x `**` exponent)
assertEquals(x `**` exponent, 100)
Run Code Online (Sandbox Code Playgroud)
注意`` - 在Kotlin中这些用于转义关键字并将它们用作实际名称.即var `this`
可以是变量名称,但必须被称为`this`
.
如果您不知道infix
关键字是什么,它可以启用没有句点和括号的调用函数.它在这里使用的原因是进行x `**` exponent
实际有效的函数调用
Sat*_*mar 10
正如其他答案所提到的,Kotlin/Java 中没有指数运算符。但是,不建议使用 Double 和 Float 中可用的扩展函数来执行 Long 的幂运算。原因如下:由于 Double 的精度限制,在求幂后将 Double 转换回 Long 会导致数字四舍五入。
val EXP = 38
println(3.toDouble().pow(EXP).toLong())
// 1350851717672992000
println(3.toDouble().pow(EXP))
// 1.350851717672992E18
Run Code Online (Sandbox Code Playgroud)
但实际答案是 13508517176729920 89。因此,我建议您使用 BigIntegers 来执行幂运算。同样也可以用于快速模幂运算。这是我们的最终pow(base, exp)
功能:
fun pow(n: Long, exp: Int): Long{
return BigInteger.valueOf(n).pow(exp).toLong()
}
Run Code Online (Sandbox Code Playgroud)
使用扩展方法POW
inline fun Double.pow(x: Double): Double (source)
Run Code Online (Sandbox Code Playgroud)
更多的细节POW
归档时间: |
|
查看次数: |
5876 次 |
最近记录: |