【问题标题】:Why is increment a bit complicated? [duplicate]为什么增量有点复杂? [复制]
【发布时间】:2021-02-21 11:23:25
【问题描述】:

这是为什么

x = 10, y = 10;
z = x++ + y++;

还是20?他们都有增量,但输出仍然是 20 为什么?但是当我这样做时

z = ++x + ++y; 

输出变为 22。为什么以及如何???有人可以向我解释吗?谢谢

【问题讨论】:

标签: c#


【解决方案1】:

你可以认为 ++x 和 x++ 如下

static int x_plus_plus(ref int x)
{
  int xp = x;
  x = x+1;
  return xp;
}

static int plus_plus_x(ref int x)
{
  x = x+1;
  return x;
}

现在,当您执行 x++ + y++ 时,x 和 y 的值会增加 1,但 x++ 返回旧的 x 值, 在 ++x 的情况下,x 增加 1 加上 (++x) 使用 x 的 新值

【讨论】:

    【解决方案2】:

    看微软Arithmetic operators (C# reference)这个描述

    还有这两个例子:

    i++首先完成操作(返回它的值)然后递增:

    int i = 3;
    Console.WriteLine(i);   // output: 3
    Console.WriteLine(i++); // output: 3
    Console.WriteLine(i);   // output: 4
    

    虽然在本例 (++a) 中,值先递增然后返回。

    double a = 1.5;
    Console.WriteLine(a);   // output: 1.5
    Console.WriteLine(++a); // output: 2.5
    Console.WriteLine(a);   // output: 2.5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 2014-06-14
      • 1970-01-01
      • 2011-01-02
      • 2015-12-08
      相关资源
      最近更新 更多