Java 方法Math.round可用于对数字进行四舍五入。以下哪个代码片段将浮点数转换为最接近的整数?
正确答案是:
double f = 4.65
int n = (int) Math.round(f);
为什么不是以下内容:
double f = 4.65;
int n = Math.round(f);
Math.round(double)返回 a long,因此是缩小演员表。
数学有两种圆形方法。
static long round(double a)
//Returns the closest long to the argument.
static int round(float a)
//Returns the closest int to the argument.
您使用的是第一个,它返回一个 long 值,它可以存储比 int 更大的整数,并且不能隐式转换为 int。
如果您将 a 传递给double,Math.Round那么您将得到 along作为结果。
只有当你通过 afloat你才会得到 aint作为结果。
来自 Java 文档:
round( double a)
返回最接近参数的long。round( float a)
返回最接近参数的int。
根据 Java DocsMath.round(double)将返回 along并且因为 along不是int你必须使用(int).