不耻下问:Java语言求绝对值,不使用if语句和函数,到底怎么实现呢
用三目运算符即可。
class Test {
public static void main(String[] args) {
int a = 8;
double b = -5.0;
System.out.println(a < 0 ? -a : a);
System.out.println(b < 0 ? -b : b);
}
}
输出:
8
5.0
参考Math.abs的实现。
/**
* 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;
}
import java.util.Scanner;
public class Day_10 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("请输入一个整数:");
int number=input.nextInt();
//数字方法:用三目运算符判断number是否大于零大于零直接输出,小于零乘以-1以便得到一个正数。
System.out.print(number+" 的绝对值为:");
System.out.println(number>0?number:number*-1);
//字符串方法:用Sting里的replace()方法代替掉“-”就可以了。
String str=""+number;
str=str.replace("-","");
int result=Integer.parseInt(str);
System.out.println(number+" 的绝对值为:"+result);
}
}
结果:
请输入一个整数:
-5954
-5954 的绝对值为:5954
-5954 的绝对值为:5954