Java中绝对值函数的介绍与其妙用
一、绝对值函数使用说明
绝对值函数是JDK中Math.java中的实现方法,其用来得到表达式的绝对值。
其实现非常简单,源码如下:
/**
*Returnstheabsolutevalueofan{@codeint}value.
*Iftheargumentisnotnegative,theargumentisreturned.
*Iftheargumentisnegative,thenegationoftheargumentisreturned.
*
*<p>Notethatiftheargumentisequaltothevalueof
*{@linkInteger#MIN_VALUE},themostnegativerepresentable
*{@codeint}value,theresultisthatsamevalue,whichis
*negative.
*
*@paramatheargumentwhoseabsolutevalueistobedetermined
*@returntheabsolutevalueoftheargument.
*/
publicstaticintabs(inta){
return(a<0)?-a:a;
}
二、绝对值的特性及其运用。
1、正数的绝对值是其本身。
2、负数的绝对值是其相反数。
3、零的绝对值是其本身。
绝对值:自减函数配合绝对值,先降序再升序。
intnumber=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)+"");
}
输出结果:
原值输出: 543210-1-2-3-4-5-6-7 绝对值输出: 5432101234567
三、案例
1、背景:输出如下图案。
A BAB CBABC DCBABCD EDCBABCDE FEDCBABCDEF GFEDCBABCDEFG
2、分析:
1、A为中心点
2、每一行,先降序,再升序
3、字母可以换算成整数,'A'=65。那么,每行首个输出字母为'A'+行数。
4、每行左右对称,每行输出字母数=行数*2+1(字母A);
3、实现
1、实现分析中的1~3步。以‘A'为中心点,先降序,再升序输出每行图案。
//调用
print(5);
/**
*先降序,再升序实现
*@paramrow
*/
privatestaticvoidprint(introw){
for(inti=0;i<2*row+1;i++){
intprintChar='A'+Math.abs(row-i);
System.out.print(((char)printChar)+"");
}
}
输出如下:
FEDCBABCDEF
2、步骤4中,每行输出字母数=行数*2+1(字母A),那么:
每行应该显示的字母除外的部分,打印空格。逻辑控制如下:
for(intj=0;j<2*row+1;j++){
//逻辑输出字母。先降序、再升序逻辑输出的字母
intprintChar='A'+Math.abs(row-j);
//如果[逻辑控制字母]大于[规定输出字母],则:
if(printChar>firstChar){
//输出空格
System.out.print("");
}else{
//输出字母
System.out.print(((char)printChar)+"");
}
}
3、完整代码:
//完整调用
printWithRow(7);
/**
*先倒序再正序输出英文大写字母
*
*@paramrow行
*/
privatestaticvoidprintWithRow(introw){
for(inti=0;i<row;i++){
//规定输出字母。每行第一个显示出来的字母
intfirstChar='A'+i;
for(intj=0;j<2*row+1;j++){
//逻辑输出字母。先降序、再升序逻辑输出的字母
intprintChar='A'+Math.abs(row-j);
//如果[逻辑控制字母]大于[规定输出字母],则:
if(printChar>firstChar){
//输出空格
System.out.print("");
}else{
//输出字母
System.out.print(((char)printChar)+"");
}
}
//输出回车
System.out.println();
}
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。