首页 > 解决方案 > 在方法中使用 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”。这背后有什么原因吗?谢谢。

标签: javafloating-pointdoublelong-integer

解决方案


在调用中:

Math.round(12.5)

12.5 被评估为 adoubleMath#round调用具有以下签名的方法 :

public static long round(double a)

因为它返回 along它会打印没有任何小数位(13)。但是,在第二个打印语句中,您使用:

public static double round(double integer) {
    return Math.round(integer);
}

它返回 a double,因此返回十进制值 13.0。


推荐阅读