Java中Math.round()的用法

今天遇到了关于Math.round()的用法的基础题,发现自己还不是太熟悉,所以来总结一下下。


Java中的Math.round()方法是将浮点型进行“四舍五入”转换为int类型的一个方法。使用细节可以看例题:

小数点后第一位等于五时:

System.out.println(Math.round(-11.5)); -> 输出为 -11
System.out.println(Math.round(11.5)); -> 输出为 12

小数点后第一位小于五时:

System.out.println(Math.round(-11.41)); -> 输出为 -11
System.out.println(Math.round(11.41)); -> 输出为 11

小数点后第一位大于五时:

System.out.println(Math.round(-11.58)); -> 输出为 -12
System.out.println(Math.round(11.58)); -> 输出为 12

代码验证:

public class main {public static void main(String[] args) {System.out.println(Math.round(-11.5));System.out.println(Math.round(11.5));System.out.println(Math.round(-11.41));System.out.println(Math.round(11.41));System.out.println(Math.round(-11.58));System.out.println(Math.round(11.58));}
}

结果图:
在这里插入图片描述

一句话结论:将括号内的数 + 0.5 向下取整即为输出。

验证结论:

小数点后第一位等于五时:

System.out.println(Math.round(-11.5)); -> -11.5 + 0.5 = -11 向下取整输出为 -11
System.out.println(Math.round(11.5)); -> 11.5 + 0.5 = 12 向下取整输出为 12

小数点后第一位小于五时:

System.out.println(Math.round(-11.41)); -> -11.41 + 0.5 = -10.91 向下取整输出为 -11
System.out.println(Math.round(11.41)); -> 11.41 + 0.5 = 11.91 向下取整输出为 11

小数点后第一位大于五时:

System.out.println(Math.round(-11.58)); -> -11.58 + 0.5 = -11.08 向下取整输出为 -12
System.out.println(Math.round(11.58)); -> 11.58 + 0.5 = 12.05 向下取整输出为 12


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部