gpt4 book ai didi

Java:前缀 - 后缀问题

转载 作者:行者123 更新时间:2023-11-30 06:24:53 26 4
gpt4 key购买 nike

我在使用前缀和后缀运算符对数字执行减法时遇到了一个小问题。这是我的程序:

public class postfixprefix  
{
public static void main (String args[])
{
int a = 5;
int b;
b = (a++) - (++a);
System.out.println("B = " +b);
}
}

这样做,理论上我应该得到 0 作为答案,但是,我得到的是 -2。

当我尝试单独尝试增加值时,就像在这个程序中一样:

public class postfixprefix  
{
public static void main (String args[])
{
int a = 5;
int b, c;
b = a++;
c = ++a;
System.out.println("B = " +b);
System.out.println("C = " +c);
}
}

我得到的值为 B = 5,C = 7。

所以我的想法是'c'从'b'中获取'a'的值(如果我错了请纠正我),但我想知道的是

  1. 我怎么能让它不从“b”中获取“a”的值,并且
  2. 使用前缀 - 后缀,减去它们时我可以得到 0 作为答案吗?

最佳答案

如果你一步一步地完成这个过程,你会看到会发生什么:

b = (a++) - (++a); //a is now 5
b = 5 - (++a); //read a, then increment it. a is now 6
b = 5 - 7; //increment a, then read it. a is now 7
b = -2

如果换一种方式,你会得到:

b = (++a) - (a++); //a is now 5
b = 6 - (a++); //increment a, then read it. a is now 6
b = 6 - 6; //read a, then increment it. a is now 7
b = 0

关于Java:前缀 - 后缀问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16460879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com