Java中絕對值函數(shù)的介紹與其妙用
一、絕對值函數(shù)使用說明
絕對值函數(shù)是JDK中Math.java
中的實現(xiàn)方法,其用來得到表達式的絕對值。
其實現(xiàn)非常簡單,源碼如下:
/** * 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. * * <p>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; }
二、絕對值的特性及其運用。
1、正數(shù)的絕對值是其本身。
2、負數(shù)的絕對值是其相反數(shù)。
3、零的絕對值是其本身。
絕對值:自減函數(shù)配合絕對值,先降序再升序。
int number = 6; System.out.println("原值輸出:"); while(number>=-6){ number --; System.out.print(number+" "); } System.out.println("\n絕對值輸出:"); number = 6; while(number>=-6){ number --; System.out.print(Math.abs(number)+" "); }
輸出結(jié)果:
原值輸出: 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
三、案例
1、背景:輸出如下圖案。
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
2、分析:
1、A為中心點
2、每一行,先降序,再升序
3、字母可以換算成整數(shù),'A' = 65。那么,每行首個輸出字母為 'A' +行數(shù)。
4、每行左右對稱,每行輸出字母數(shù) = 行數(shù)*2 +1(字母A);
3、實現(xiàn)
1、實現(xiàn)分析中的1~3步。以‘A'為中心點,先降序,再升序輸出每行圖案。
//調(diào)用 print(5); /** * 先降序,再升序 實現(xiàn) * @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中,每行輸出字母數(shù) = 行數(shù)*2 +1(字母A),那么:
每行應(yīng)該顯示的字母除外的部分,打印空格。邏輯控制如下:
for(int j=0;j<2*row+1;j++){ //邏輯輸出字母。先降序、再升序邏輯輸出的字母 int printChar = 'A' + Math.abs(row-j); //如果 [邏輯控制字母] 大于 [規(guī)定輸出字母],則: if(printChar>firstChar){ //輸出空格 System.out.print(" "); }else{ //輸出字母 System.out.print(((char)printChar)+" "); } }
3、完整代碼:
//完整調(diào)用 printWithRow(7); /** * 先倒序 再正序 輸出 英文大寫字母 * * @param row 行 */ private static void printWithRow(int row){ for(int i=0;i<row;i++){ //規(guī)定輸出字母。每行第一個顯示出來的字母 int firstChar = 'A' + i; for(int j=0;j<2*row+1;j++){ //邏輯輸出字母。先降序、再升序邏輯輸出的字母 int printChar = 'A' + Math.abs(row-j); //如果 [邏輯控制字母] 大于 [規(guī)定輸出字母],則: if(printChar>firstChar){ //輸出空格 System.out.print(" "); }else{ //輸出字母 System.out.print(((char)printChar)+" "); } } //輸出回車 System.out.println(); } }
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
相關(guān)文章
淺談springfox-swagger原理解析與使用過程中遇到的坑
本篇文章主要介紹了淺談springfox-swagger原理解析與使用過程中遇到的坑,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02Spring動態(tài)多數(shù)據(jù)源配置實例Demo
本篇文章主要介紹了Spring動態(tài)多數(shù)據(jù)源配置實例Demo,具有一定的參考價值,有興趣的可以了解一下。2017-01-01Java8中LocalDateTime與時間戳timestamp的互相轉(zhuǎn)換
這篇文章主要給大家介紹了關(guān)于Java8中LocalDateTime與時間戳timestamp的互相轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03