[英]Why does the following code require the (int)?
The Java method Math.round
can be used to round numbers. Java方法
Math.round
可以用于舍入数字。 Which of the following code fragments converts a floating-point number to the nearest integer? 以下哪个代码片段将浮点数转换为最接近的整数?
The right answer is: 正确的答案是:
double f = 4.65
int n = (int) Math.round(f);
Why is it not the following: 为什么不是以下原因:
double f = 4.65;
int n = Math.round(f);
Math.round(double)
返回long
,因此缩小范围。
Math has two round methods. 数学有两种舍入方法。
static long round(double a)
//Returns the closest long to the argument.
static int round(float a)
//Returns the closest int to the argument.
You are using the first one, which returns a long value, which can store larger integers than int, and cannot be implicitly cast to int. 您正在使用第一个返回长值的值,该值可以存储比int大的整数,并且不能隐式转换为int。
If you pass a double
to Math.Round
then you get a long
as result. 如果您将
double
Math.Round
传递给Math.Round
那么结果将long
。
only if you pass a float
you get a int
as result. 仅当您通过
float
您才能得到一个int
结果。
From the Java Docs: 从Java文档中:
round( double a)
圆( 双 )
Returns the closest long to the argument.返回最接近参数的long 。
round( float a)
圆形( 浮点 )
Returns the closest int to the argument.返回与参数最接近的整数 。
根据Java文档, Math.round(double)
将返回long
并且因为long
不是int
,因此必须使用(int)
进行(int)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.