java - 在方法中使用 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。
推荐阅读
- filter - 从 Ansible 中的字符串中删除最后 n 个字符
- python - 在 Dash-plotly 按钮上运行 python 脚本
- node.js - 如何在node.js中配置不同服务器的dburl?
- windows - Jboss 7.2 - [org.jboss.config] file.encoding - Jboss 作为 Windows 服务
- javascript - 在反应中刷新后路由未定义
- python - os.path.abspath 忽略最后一个目录
- c++ - nullptr 访问类方法 VS 静态方法
- excel - 允许网络上的其他人在我的本地 PC 上打开工作簿
- sql - 无法在更新 postgres 中使用除外
- ansible - 如果在 Ansible 中可以访问第一台主机,则跳过其他主机