Java程序将正整数转换为负数,并将负整数转换为正数
要将正整数转换为负整数,反之亦然,请使用按位补码运算符(~)。
让我们首先初始化一个正整数-
int positiveVal = 200;
现在,让我们将其转换为负数-
int negativeVal = (~(positiveVal - 1));
现在,我们有以下负数int-
int negativeVal = -300;
以下将负数转换为正数int-
positiveVal = ~(negativeVal - 1);
示例
public class Demo {public static void main(String[] args) throws java.lang.Exception {
int positiveVal = 100;
int negativeVal = (~(positiveVal - 1));
System.out.println("结果:正值转换为负值 = "+negativeVal);
positiveVal = ~(negativeVal - 1);
System.out.println("实际正值 = "+positiveVal);
negativeVal = -200;
System.out.println("实际负值 = "+negativeVal);
positiveVal = ~(negativeVal - 1);
System.out.println("结果:负值转换为正值 = "+positiveVal);
}
}
输出结果
结果:正值转换为负值 = -100实际正值 = 100
实际负值 = -200
结果:负值转换为正值 = 200
以上是 Java程序将正整数转换为负数,并将负整数转换为正数 的全部内容, 来源链接: utcz.com/z/355588.html