国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java中絕對值函數的介紹與其妙用

2019-11-26 13:19:19
字體:
來源:轉載
供稿:網友

一、絕對值函數使用說明

絕對值函數是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. * * <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、正數的絕對值是其本身。

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

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

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

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)+" ");}

輸出結果:

原值輸出: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、字母可以換算成整數,'A' = 65。那么,每行首個輸出字母為 'A' +行數。

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

3、實現

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<row;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(); }}

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 廊坊市| 黔西县| 马公市| 林西县| 响水县| 银川市| 华亭县| 新余市| 灵台县| 黄平县| 綦江县| 蛟河市| 大埔县| 美姑县| 电白县| 敦化市| 宝鸡市| 连城县| 湘乡市| 孟州市| 宁南县| 鄂托克旗| 张掖市| 盐池县| 贵德县| 新河县| 定南县| 花垣县| 砚山县| 青龙| 丹巴县| 云安县| 商水县| 沂水县| 南丰县| 深水埗区| 垣曲县| 朔州市| 西丰县| 大田县| 大田县|