要将负数转换为正数(这称为绝对值),请使用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://mkyong.com/java/how-to-convert-negative-number-to-positive-in-java/
推荐阅读--
球分享
球点赞
球在看