c# - 加法与预增量失去 1

标签 c# operators pre-increment

<分区>

为什么 TestAddition 结果是 12 而不是 13?它应该是 5 + 1 + 7 = 13,但是断言失败了

Expected: 13

But was: 12

int method(int a)
{
    return 7;
}

[Test]
public void TestAddition()
{
    int row = 5;
    row += method(++row);

    Assert.AreEqual(13, row, "Why is it twelve instead of 13?");
}

最佳答案

因为你的

row += method(++row);

等于

row = row + method(++row);

+ operatorleft associative ,它将第一个 row 计算为 5 并且 method 总是返回 7 无论如何它需要哪个参数。

row = row + method(++row);
       ^          ^
       5          7

这就是为什么结果会是 12

关于c# - 加法与预增量失去 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33709413/

相关文章:

python - 函数调用中的星号

java - 为什么 Integer.MIN_VALUE 的负数给出相同的值?

c++ - 在 C++ 中递增 - 何时使用 x++ 或++x?

c# - 如何自动同步sql行号和ID列

c# - 如何遍历表行

c# - 与数据绑定(bind)转发器控件一起使用时如何清理查询字符串?

c++ - 类外的 'OPairType::OPairType(int, int)' 声明不是定义

c++ - 将递增/递减运算符传递给函数

c - C 语言 gcc 编译器中前后增量的意外行为

c# - 对固定 block 内的指针所做的更改是否保留?