totalAmount的增量和减量

时间:2012-03-10 14:15:58

标签: c# increment decrement

namespace rojak2.cs
{
    class Program
    {
        static void Main(string[] args)
        {
            ArithmeticOperators();
        }

        static void ArithmeticOperators()
        {
            double totalAmount = 100;
            double result;

            Console.WriteLine("totalAmount is {0}", totalAmount);
            Console.WriteLine();

            result = totalAmount + 100;
            Console.WriteLine("totaAmount is {0}", result);

            result = totalAmount - 50;
            Console.WriteLine("totaAmount is {0}", result);

            result = ++totalAmount;
            Console.WriteLine("totaAmount is {0}", totalAmount);

            result = --totalAmount;
            Console.WriteLine("totaAmount is {0}", totalAmount);
        }
    }

}

我的问题是为什么结果的最后输出是100而不是99?它应该从100减少到101.我不太明白。

3 个答案:

答案 0 :(得分:2)

因为前增加。变量值在其值复制到结果之前会递增。因此,结果将具有101作为预先递增的结果以及递减 - 它首先减去一个然后复制值,因此得到结果为100.

答案 1 :(得分:1)

  

应该从100减少到101

为什么呢?您可以在此声明之前告诉 totalAmount是101,因为这是上一行的输出!

让我们看看变量在代码过程中如何变化:

double totalAmount = 100;
double result;
result = totalAmount + 100;

// totalAmount = 100; result = 200

result = totalAmount - 50;

// totalAmount = 100; result = 50

result = ++totalAmount;

// totalAmount = 101, result = 101

result = --totalAmount;

// totalAmount = 100, result = 100

我怀疑这是令你困惑的前缀增量/减量。

本声明:

result = ++totalAmount;

基本上相当于:

totalAmount = totalAmount + 1;
result = totalAmount;

答案 2 :(得分:1)

该行

result = ++totalAmount;

不仅更改result,还更改totalAmount;这就是为什么在最后一行,它是101,而不是100