Math.round()(Java)
Description(英文原文描述)
If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞.
(个人见解)
不管Math.round()中的参数如何,无非就是两个方向的取法,向更大或者向更小【如Math.round(11.54)不是11就是12】。
思路:
1.如果参数的小数部分刚好为0.5,则将参数舍为(往+∞方向)最近的整数。
2.如果参数的小数部分大于0.5,则取邻近整数中绝对值较大的邻近整数(这里的邻近整数意思是参数旁边的两个整数,如11.46的两个邻近整数11和12)
3.如果参数的小数部分小于0.5,则取邻近整数中绝对值较小的邻近整数
计算方法:
1.如果参数的小数部分刚好为0.5,则将参数舍为(往+∞方向)最近的整数。[如11.5舍为(往+∞方向)12、-11.5舍为(往+∞方向)-11]
2.如果参数的小数部分大于或者小于0.5
先计算出参数邻近的两个整数(如-20.49邻近整数,-20、-21),
取两个邻近整数-20、-21的绝对值20、21。
2.1如果参数的小数部分大于0.5,取绝对值更大的邻近整数(这里邻近整数-21的绝对值为21大于-20的绝对值20)-21
2.2如果参数的小数部分小于0.5,取绝对值更小的邻近整数(这里邻近整数-20的绝对值为20小于-21的绝对值21)-20
官方测试用例:
Math.round( 20.49); // 20
Math.round( 20.5 ); // 21
Math.round( 42 ); // 42
Math.round(-20.5 ); // -20
Math.round(-20.51); // -21
由于编者水平所限,个人见解中难免存在一些缺点和错误,殷切希望读者批评指正。