要将负数转换为正数(这称为绝对值),请使用Math.abs() 。此Math.abs()
方法的工作方式如下:“ number = (number < 0 ? -number : number);
”。
看一个完整的例子:
package com.mkyong; public class app{ public static void main(String[] args) { int total = 1 + 1 + 1 + 1 + (-1); //output 3 System.out.println("Total : " + total); int total2 = 1 + 1 + 1 + 1 + Math.abs(-1); //output 5 System.out.println("Total 2 (absolute value) : " + total2); } }
输出量
Total : 3 Total 2 (absolute value) : 5
在这种情况下, Math.abs(-1)
会将负数1转换为正数1。
原文:https://www.cnblogs.com/summerxbc/p/14247907.html