在方法中使用Math.round()与直接使用
我在这里有这个代码:
public class Main {
public static void main(String[] args) {
System.out.println(Math.round(12.5));
System.out.println(round(12.5));
}
public static double round(double integer) {
return Math.round(integer);
}
}
当我运行代码时,它输出:
13
13.0
为什么当我Math.round()在main方法中正常运行时,它提供一个整数值,而在“round”方法中提供一个double值?我知道我的方法是“double”类型,但 Java 不允许我将其更改为“int”。这背后有什么原因吗?谢谢。
回答
在调用中:
Math.round(12.5)
12.5 被评估为 adouble并且Math#round调用具有以下签名的方法 :
public static long round(double a)
因为它返回 along它将打印没有任何小数位(即13)。但是,在第二个打印语句中,您使用:
public static double round(double integer) {
return Math.round(integer);
}
它返回 a double,因此十进制值 13.0。