x--或x ++在这里做什么?

Nan*_*ana 1 java

对于大多数人来说,这是一个愚蠢的问题 - 我知道 - 但我是这里的初学者之一,我无法理解为什么这里的输出是12(x--这对于结果做了什么)?

int x, y;
x = 7;
x-- ;
y = x * 2;
x = 3;
Run Code Online (Sandbox Code Playgroud)

dar*_*ioo 13

x--将减值值减x1.它是一个后缀减量运算符,--x是一个前缀减量运算符.

那么,这里发生了什么?

 
int x, y;    //initialize x and y
x = 7;       //set x to value 7
x--;         //x is decremented by 1, so it becomes 6
y = x * 2;   //y becomes 6*2, therefore y becomes 12
x = 3;       //x becomes 3

通过类比,++将值增加1.它还具有前缀和后缀变体.


Nim*_*sky 7

x-- 将x的值减1 /减1.

Conversley x++增加/增加一个.

加号或减号可以是变量名,前缀后缀之前(--x)或之后(x--).如果在表达式中使用,则前缀将在执行操作后返回值,后缀将在执行操作之前返回值.

int x = 0;
int y = 0;
y = ++x; // y=1, x=1

int x = 0;
int y = 0;
y = x++;// y=0, x=1
Run Code Online (Sandbox Code Playgroud)

  • 它将值3赋给x. (2认同)

Pow*_*eke 5

--是'减量'运算符.它只是意味着它操作的变量(在这种情况下是x变量)得到的减1.

基本上它是简写:

x = x - 1;
Run Code Online (Sandbox Code Playgroud)

那么代码的作用是什么:

int x,y ; # Define two variables that will hold an integer
x=7;      # Set variable X to value 7
x-- ;     # Decrement x by one : so x equals 7 - 1 = 6
y= x * 2; # Multiply x by two and set the result to the y variable: 6 times 2 equals 12
x=3;      # set x to value 3 (I do not know why this is here).
Run Code Online (Sandbox Code Playgroud)