The Java method Math.round
can be used to round numbers. 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.
If you pass a double
to Math.Round
then you get a long
as result.
only if you pass a float
you get a int
as result.
From the Java Docs:
round( double a)
Returns the closest long to the argument.round( float a)
Returns the closest int to the argument.
根据Java文档, Math.round(double)
将返回long
并且因为long
不是int
,因此必须使用(int)
进行(int)
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.