简体   繁体   English

totalAmount的增量和减量

[英]the totalAmount of increment and 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);
        }
    }

}

my question is why the last output of result is 100 not 99? 我的问题是为什么结果的最后输出是100而不是99? it should be decreased from 100 not 101. I dont quite get it. 它应该从100减少到101.我不太明白。

because of preincrement. 因为前增量。 Variable value gets incremented before its value gets copied to the result. 变量值在其值复制到结果之前会递增。 So result will have 101 as an outcome of preincrement and also for decrement - it subtracts one first and then copies value, hence you get result as 100. 因此,结果将具有101作为预先递增的结果以及递减 - 它首先减去一个然后复制值,因此得到结果为100。

It should be decreased from 100 not 101 它应该从100减少到101

Why? 为什么? You can tell that totalAmount is 101 before this statement, as that's the output of the previous line! 您可以在此语句之前判断 totalAmount是101,因为这是前一行的输出!

Let's look at how the variables change over the course of the code: 让我们看一下变量在代码过程中如何变化:

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

I suspect it's the prefix increment/decrement that's confusing you. 我怀疑这是令你困惑的前缀增量/减量。

This statement: 这个说法:

result = ++totalAmount;

Is basically equivalent to: 基本上相当于:

totalAmount = totalAmount + 1;
result = totalAmount;

The line 这条线

result = ++totalAmount;

Changes not only result , but totalAmount too; 变化不仅会resulttotalAmount result totalAmount ; That's why on last line, it's 101, not 100 这就是为什么在最后一行,它是101,而不是100

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

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