java 中的 Math.round(-1.5) 等于多少?
这道题目的答案是 -1.
其实这道题目考察的主要知识点就是:Math.round方法的概念以及返回值类型。
注意:Math的round方法是四舍五入,如果参数是负数,则往大的数如,Math.round(-1.5)=-1,如果是Math.round(1.5)则结果为2
计算规则为:
- 如果参数大于 Long.MAX_VALUE 则返回Long.MAX_VALUE
- 如果参数小于Long.MIN_VALUE 则返回Long.MIN_VALUE
- 如果参数为NaN则返回0
- 其余值则返回接近于当前参数的最大整数值。
所以Math.round(-1.5)返回的是最接近的最大整数-1。
例:
public class test {
public static void main(String[] args){
System.out.println(Math.round(1.3)); //1
System.out.println(Math.round(1.4)); //1
System.out.println(Math.round(1.5)); //2
System.out.println(Math.round(1.6)); //2
System.out.println(Math.round(1.7)); //2
System.out.println(Math.round(-1.3)); //-1
System.out.println(Math.round(-1.4)); //-1
System.out.println(Math.round(-1.5)); //-1
System.out.println(Math.round(-1.6)); //-2
System.out.println(Math.round(-1.7)); //-2
}
}