为什么以下代码需要(int)?

Ada*_*les 1 java object

Java方法Math.round可用于舍入数字.以下哪个代码片段将浮点数转换为最接近的整数?

正确的答案是:

double f = 4.65          
int n = (int) Math.round(f);
Run Code Online (Sandbox Code Playgroud)

为什么不是以下内容:

double f = 4.65;      
int n = Math.round(f);
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 7

Math.round(double)返回a long,因此缩小演员阵容.

  • 是的,不要写`int n = Math.round((float)f);` - 它不那么准确.`(int)Math.round(123456789.4)`是`123456789`但是`Math.round((float)123456789.4)`是`123456792`并且原因太长而无法放入评论中. (2认同)

Ram*_*oza 6

数学有两种圆形方法.

static long round(double a) 
//Returns the closest long to the argument.

static int round(float a) 
//Returns the closest int to the argument.
Run Code Online (Sandbox Code Playgroud)

您正在使用第一个,它返回一个long值,它可以存储比int更大的整数,并且不能隐式转换为int.