2012-03-10 87 views
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); 
     } 
    } 

} 

我的問題是爲什麼最後輸出的結果是100不是99?它應該從100而不是101減少。我不太明白。總增量和減量

+1

以'.cs'結尾的命名空間名稱真的很奇怪,因爲命名空間不需要(也不應該!)與文件一對一映射。 – svick 2012-03-10 14:26:44

回答

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
因爲前增量的

。在將值複製到結果之前,變量值會增加。所以導致將有101前增量的結果,也爲遞減 - 它首先減去一個,然後拷貝值,因此你得到結果爲100

1

result = ++totalAmount; 

變化不僅result,但totalAmount;這就是爲什麼在最後一行,它是101,而不是100