Java中Math.abs(Integer.MIN_VALUE)的值是其本身!

yoyochina發表於2009-02-18

如下面的程式碼:

 

public class Test
{
	private static final int N = 3;
	
	public static void main(String[] args)
	{
		for(int i=Integer.MIN_VALUE; i<Integer.MIN_VALUE+5; i++)
			System.out.println(Math.abs(i)%N);
	}
}

 

輸出結果為:

-2
1
0
2
1

 

      我們知道,對一個正整數進行取餘操作,其結果是一個非負整數。而對一個負整數進行絕對值運算,其結果是一個正整數。那這裡為什麼會出現出現一個負數呢?

 

如下面的程式碼:

 

public class Test
{
	public static void main(String[] args)
	{
		for(int i=Integer.MIN_VALUE; i<Integer.MIN_VALUE+5; i++)
			System.out.println(Math.abs(i));
	}
}

 

輸出結果為:

-2147483648
2147483647
2147483646
2147483645
2147483644

 

      也就是說,Math.abs(Integer.MIN_VALUE)的值還是其本身。通過查閱Java的API文件,我們看到對abs(int a)運算,“如果引數等於 Integer.MIN_VALUE 的值(即能夠表示的最小負 int 值),那麼結果與該值相同且為負。”所以會有這樣的結果。

 

      這樣也就出現了一個問題,即上面的取餘操作不是很合適的。下面的程式碼展示了一個真正的取餘運算。

 

public class Test
{
	private static final int N = 3;
	
	public static void main(String[] args)
	{
		int result = 0;
		
		for(int i=Integer.MIN_VALUE; i<Integer.MIN_VALUE+5; i++)
		{
			result = Math.abs(i) % N;
			System.out.println(result < 0 ? (result + N) : result);
		}
			
	}
}

 

 輸出結果為:

1
1
0
2
1

 

相關文章