Java Math類的三個方法ceil,floor,round用法
Math類的ceil,floor,round用法
ceil()方法
就表示向上取整,Math.ceil(12.3)的結果是13,Math.ceil(-12.7)的結果-12;
floor()方法
就表示向下取整,Math.floor(12.7)的結果是12,Math.floor(-12.3)的結果-13;
round()方法
表示“四舍五入”,Math.round(12.3)的結果是12,Math.round(-12.7)的結果-13;
Math的 floor,round和ceil總結
floor 返回不大于的最大整數(shù)
round 則是4舍5入的計算,入的時候是到大于它的整數(shù)
round方法,它表示“四舍五入”,算法為Math.floor(x+0.5),即將原來的數(shù)字加上0.5后再向下取整,所以,Math.round(11.5)的結果為12,Math.round(-11.5)的結果為-11。
ceil 則是不小于他的最小整數(shù)
看例子
Math.floor | Math.round | Math.ceil | |
1.4 | 1 | 1 | 2 |
1.5 | 1 | 2 | 2 |
1.6 | 1 | 2 | 2 |
-1.4 | -2 | -1 | -1 |
-1.5 | -2 | -1 | -1 |
-1.6 | -2 | -2 | -1 |
測試程序如下:
public class MyTest { public static void main(String[] args) { double[] nums = { 1.4, 1.5, 1.6, -1.4, -1.5, -1.6 }; for (double num : nums) { test(num); } } private static void test(double num) { System.out.println("Math.floor(" + num + ")=" + Math.floor(num)); System.out.println("Math.round(" + num + ")=" + Math.round(num)); System.out.println("Math.ceil(" + num + ")=" + Math.ceil(num)); } }
運行結果
Math.floor(1.4)=1.0
Math.round(1.4)=1
Math.ceil(1.4)=2.0
Math.floor(1.5)=1.0
Math.round(1.5)=2
Math.ceil(1.5)=2.0
Math.floor(1.6)=1.0
Math.round(1.6)=2
Math.ceil(1.6)=2.0
Math.floor(-1.4)=-2.0
Math.round(-1.4)=-1
Math.ceil(-1.4)=-1.0
Math.floor(-1.5)=-2.0
Math.round(-1.5)=-1
Math.ceil(-1.5)=-1.0
Math.floor(-1.6)=-2.0
Math.round(-1.6)=-2
Math.ceil(-1.6)=-1.0
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringBoot整合Web開發(fā)之Json數(shù)據(jù)返回的實現(xiàn)
這篇文章主要介紹了SpringBoot整合Web開發(fā)其中Json數(shù)據(jù)返回的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08JavaSE的三大接口:Comparator,Comparable和Cloneable詳解
這篇文章主要介紹了詳解JavaSE中Comparator,Comparable和Cloneable接口的區(qū)別的相關資料,希望通過本文大家能徹底掌握這部分內容,需要的朋友可以參考下2021-10-10springboot controller參數(shù)注入方式
這篇文章主要介紹了springboot controller參數(shù)注入方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05解決Java導入excel大量數(shù)據(jù)出現(xiàn)內存溢出的問題
今天小編就為大家分享一篇解決Java導入excel大量數(shù)據(jù)出現(xiàn)內存溢出的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06