作者No (you stay there)
看板java
标题Re: [请问] 一条爪哇问题
时间Thu Jun 9 00:39:28 2011
※ 引述《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 / (365
L * 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)
1F:推 badbadook: Integer.MIN_VALUE == -Integer.MIN_VALUE 06/09 01:04