简体   繁体   English

整数的奇怪行为

[英]strange behavior of integers

I have the following code 我有以下代码

 int a = 1, n = 1;

Convert.ToInt32(a = a++ + n--);

Console.WriteLine("a: " + a + " n : " + n);

//If you debug the second line of the code in quick watch the answer is 3.

The answer to above code should be 2, so it is. 上面的代码的答案应该为2。 But if i debug it and see the value in quickwatch the value of a is printed 3. Any idea why the same code results two different values. 但是,如果我调试它并在quickwatch中看到该值,则会打印出a的值。3.知道为什么相同的代码会导致两个不同的值。

Also note that the increment/decrement operators tailing the variables will be executed after the variable is used in the calculation (but before the result is written into a). 还要注意,尾随变量的递增/递减运算符将在计算中使用变量之后(但将结果写入a之前)执行。

This will be interpreted as a= 1 +1, not a = 2 + 0 这将被解释为a = 1 +1,而不是a = 2 + 0

Specifcally the programm flows: 具体来说,程序流程如下:

Take 1 out of 'a' into calculation memory. 从“ a”中取出1到计算存储器中。

Increment 'a' by 1 将“ a”加1

take 1 out of 'n' into calculation memory 从n中取1到计算存储器

Decrement 'n' by 1 将n减1

Set 'a' to the sum of the two values you extracted earlier (not the current values of those variables) Often putting seperate steps into seperate lines can yield a lot better debugging. 将“ a”设置为您先前提取的两个值的总和(而不是这些变量的当前值),通常将单独的步骤放到单独的行中可以产生更好的调试效果。 ie: 即:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM