How to convert negative number to positive in Java?

来源:互联网 发布:淘宝旺铺基础版装修 编辑:程序博客网 时间:2024/06/05 17:03
To convert negative number to positive number (this is called absolute value), uses Math.abs(). This Math.abs() method is work like this “number = (number < 0 ? -number : number);".

See a complete example :

/** * 测试负数转正数 */@Testpublic void test2() {// TODO Auto-generated method stubint total = 1 + 1 + 1 + 1 + (-1);// output 3System.out.println("Total:" + total);int total2 = 1 + 1 + 1 + 1 + Math.abs(-1);// output 5System.out.println("Total 2 (absolute value):" + total2);}

Output:

Total : 3Total 2 (absolute value) : 5
In this case, Math.abs(-1) will convert the negative number 1 to positive 1.

原创粉丝点击