1
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? it should be decreased from 100 not 101. I dont quite get it.

svick
  • 236,525
  • 50
  • 385
  • 514
George Lim
  • 145
  • 1
  • 2
  • 8
  • 1
    Having a namespace name ending with `.cs` is really weird, because namespaces don't have to (and shouldn't!) map one to one with files. – svick Mar 10 '12 at 14:26

3 Answers3

2

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.

DotNetUser
  • 6,494
  • 1
  • 25
  • 27
1

It should be decreased from 100 not 101

Why? You can tell that totalAmount is 101 before this statement, as that's the output of the previous line!

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;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

The line

result = ++totalAmount;

Changes not only result, but totalAmount too; That's why on last line, it's 101, not 100

archil
  • 39,013
  • 7
  • 65
  • 82