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)
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.
Run Code Online (Sandbox Code Playgroud)
您正在使用第一个,它返回一个long值,它可以存储比int更大的整数,并且不能隐式转换为int.