Java中Math.round()的用法及说明

 更新时间:2024年02月24日 15:38:46   作者:木木是木木  
这篇文章主要介绍了Java中Math.round()的用法及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

最新评论