IT科技

當前位置 /首頁/IT科技 > /列表

java中絕對值函數怎麼用

一、絕對值函數使用説明

絕對值函數是JDK中Math.java中的實現方法,其用來得到表達式的絕對值。

其實現非常簡單,源碼如下:

/**

* Returns the absolute value of an {@code int} value.

* If the argument is not negative, the argument is returned.

* If the argument is negative, the negation of the argument is returned.

*

*

Note that if the argument is equal to the value of

* {@link Integer#MIN_VALUE}, the most negative representable

* {@code int} value, the result is that same value, which is

* negative.

*

* @param a the argument whose absolute value is to be determined

* @return the absolute value of the argument.

*/

public static int abs(int a) {

return (a < 0) ? -a : a;

}

java中絕對值函數怎麼用

二、絕對值的特性及其運用。

1、正數的絕對值是其本身。

2、負數的絕對值是其相反數。

3、零的絕對值是其本身。

絕對值:自減函數配合絕對值,先降序再升序。

int number = 6;

System.out.println("原值輸出:");

while(number>=-6){

number --;

System.out.print(number+" ");

}

System.out.println("絕對值輸出:");

number = 6;

while(number>=-6){

number --;

System.out.print(Math.abs(number)+" ");

}

輸出結果:

原值輸出:

5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7

絕對值輸出:

5 4 3 2 1 0 1 2 3 4 5 6 7

java中絕對值函數怎麼用 第2張

案例

背景:輸出如下圖案。

A

B A B

C B A B C

D C B A B C D

E D C B A B C D E

F E D C B A B C D E F

G F E D C B A B C D E F G

分析:

1、A為中心點

2、每一行,先降序,再升序

3、字母可以換算成整數,'A' = 65。那麼,每行首個輸出字母為 'A' +行數。

4、每行左右對稱,每行輸出字母數 = 行數*2 +1(字母A);

實現:

1、實現分析中的1~3步。以‘A’為中心點,先降序,再升序輸出每行圖案。

//調用

print(5);

/**

* 先降序,再升序 實現

* @param row

*/

private static void print(int row){

for(int i=0;i<2*row+1;i++){

int printChar = 'A' + Math.abs(row-i);

System.out.print(((char)printChar)+" ");

}

}

輸出如下:

F E D C B A B C D E F

2、步驟4中,每行輸出字母數 = 行數*2 +1(字母A),那麼:

每行應該顯示的字母除外的部分,打印空格。邏輯控制如下:

for(int j=0;j<2*row+1;j++){

//邏輯輸出字母。先降序、再升序邏輯輸出的字母

int printChar = 'A' + Math.abs(row-j);

//如果 [邏輯控制字母] 大於 [規定輸出字母],則:

if(printChar>firstChar){

//輸出空格

System.out.print(" ");

}else{

//輸出字母

System.out.print(((char)printChar)+" ");

}

}

3、完整代碼:

//完整調用

printWithRow(7);

/**

* 先倒序 再正序 輸出 英文大寫字母

*

* @param row 行

*/

private static void printWithRow(int row){

for(int i=0;i

//規定輸出字母。每行第一個顯示出來的字母

int firstChar = 'A' + i;

for(int j=0;j<2*row+1;j++){

//邏輯輸出字母。先降序、再升序邏輯輸出的字母

int printChar = 'A' + Math.abs(row-j);

//如果 [邏輯控制字母] 大於 [規定輸出字母],則:

if(printChar>firstChar){

//輸出空格

System.out.print(" ");

}else{

//輸出字母

System.out.print(((char)printChar)+" ");

}

}

//輸出回車

System.out.println();

}

}

TAG標籤:java 函數 絕對值 #