Java 中怎么把负数转换为正数?

要将负数转换为正数(这称为绝对值),请使用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。  

  

posted @ 2021-01-07 18:16  summer_xbc  阅读(12319)  评论(0编辑  收藏  举报