科特林 |带有示例的 Math.abs() 方法
Math.abs()函数返回给定参数的绝对值。如果参数为非负数,则返回参数本身。而如果参数为负,则返回它的否定值。基本上,它在数学中用作模函数。
Syntax : fun abs(x : DataType) : DataType
Parameters: It can take values of Data type int, double, long, float.
Returns: It returns absolute value of the argument, without changing the data type.
Exceptions:
- If the argument is NaN, the result is NaN.
- If the argument is Int.MIN_VALUE, the result is that same value, Int.MIN_VALUE, which is negative.
- If the argument is Long.MIN_VALUE, the result if that same value, Long.MIN_VALUE, which is negative.
代码 #1:将浮点和双精度数据类型作为参数。
// Kotlin program to illustrate
// working of Math.abs() method
import kotlin.math.abs
fun main(args : Array){
val f = -45.23f;
val d = 999.32;
// abs() function taking float as input
println(abs(f));
// abs() function taking double as input
println(abs(d));
}
输出:
45.23
999.32
代码 #2:将 int 和 long 数据类型作为参数。
// Kotlin program to illustrate
// working of Math.abs() method
import kotlin.math.abs
fun main(args : Array){
val i = -0;
val l = -69973688;
// abs() function taking int as input
println(abs(i));
println(abs(Int.MIN_VALUE));
// abs() function taking long as input
println(abs(l));
println(abs(Long.MIN_VALUE));
}
输出:
0
-2147483648
69973688
-9223372036854775808