Java:前缀 - 后缀问题 [英] Java: Prefix - Postfix issue
本文介绍了Java:前缀 - 后缀问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用前缀和后缀运算符对数字执行减法时遇到了一个小问题.这是我的程序:
I have a small issue performing a subtraction on numbers using prefix and postfix operators. This is my program:
public class postfixprefix
{
public static void main (String args[])
{
int a = 5;
int b;
b = (a++) - (++a);
System.out.println("B = " +b);
}
}
这样做,理论上我应该得到 0 作为答案,但是,我得到的是 -2.
Doing this, theoretically I am supposed to get 0 as the answer, but however, I am getting a -2.
当我尝试单独尝试增加此程序中的值时:
When I try to individually try to increment the values like in this program:
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.
I get the values as B = 5, C = 7.
所以我知道'c'从'b'中获取'a'的值(如果我错了,请纠正我),但我想知道的是
So i get the idea that 'c' takes the value of 'a' from 'b' (Please correct me if i am wrong), but what I want to know is
- 我怎么能不从 'b' 中取出 'a' 的值,并且
- 使用前缀 - 后缀,我可以在减去它们时得到 0 作为答案.
推荐答案
b = a++;意思是:
b = a++; means:
- 将 a 的值赋给 b
- 将 a 增加 1
c = ++a意思是:
c = ++a means:
- 将 a 增加 1
- 将 a 的值赋给 c
b = (a++) - (++a)意思是:
b = (a++) - (++a) means:
- 获取 a (5) 的值(a 没有 ++)
- 将 a 的值增加 1(从而使其为 6)(a++ 的结果)
- 将 a 增加 1 (++a)(从而使其成为 7)
- 分配给 b 值 5-7=-2(步骤 1 中的 5,步骤 3 中的 7)
这篇关于Java:前缀 - 后缀问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文