Re: [請問] 一條爪哇問題

看板java作者 (you stay there)時間14年前 (2011/06/09 00:39), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/3 (看更多)
※ 引述《badbadook ( 嗨浪)》之銘言: : public static void main(String[] args) throws Exception { : DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); : Date birth = dateFormat.parse("1966-08-08"); : Date current = new Date(); : long life = current.getTime() - birth.getTime(); : System.out.println("你今年的歲數為:" + (life / (365 * 24 * 60 * 60 : * 1000))); }} : 為何歲數爆掉是因為? 回頭看一下那教學網頁的上面就有寫到 當你在程式中寫下一個整數時,預設是使用不超過int型態的長度 所以 (365 * 24 * 60 * 60 * 1000) 這一段因為在括號內先運算 都是用int型態去乘的,當超出int最大值時,超過的位元就遺失掉 所以算出來比預期結果小很多,甚至可能還突然變負值 然後才去和long型態的life運算 而此時運算的型態不相同 這個值到這時才被轉型為long去和life運算 也因為前面的int運算就遺失位元了,歲數也就爆掉了 要解這個問題只要加一個L先將其中一個預設int改為long 之後剩下的值compiler就會幫你轉型 System.out.println("你今年的歲數為:" + (life / (365L * 24 * 60 * 60 * 1000))); : public class Main { public static void main(String[] args) { : System.out.println(Integer.MIN_VALUE == -Integer.MIN_VALUE); }} : 為何為true阿 不是沒有用""括起來 不是同一物件 Integer.MIN_VALUE 取出來是int型態: -2147483648 加上負號變成 2147483648 超過 Integer.MAX_VALUE: 2147483647 再看一下java的int是用2的補數表示法,第32個bit表示正負號,就會發現 -2147483648 = 10000000000000000000000000000000 (2進位) 2147483647 = 01111111111111111111111111111111 (2進位) 2147483647 + 1 = 10000000000000000000000000000000 (2進位) 因此那個結果才會是true -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.252.67.230 ※ 編輯: No 來自: 111.252.67.230 (06/09 00:41)

06/09 01:04, , 1F
Integer.MIN_VALUE == -Integer.MIN_VALUE
06/09 01:04, 1F
文章代碼(AID): #1DxwN3ct (java)
討論串 (同標題文章)
文章代碼(AID): #1DxwN3ct (java)