執行數學運算

已完成

Tip

有關更多詳細信息,請參閱 文本和圖像 選項卡!

電腦本質上是極其快速的計算機。 C# 支援所有標準的數學運算,讓你能進行計算並將結果儲存在變數中。

算術運算子

C# 使用標準符號進行基本數學:

Operator 動作 範例 結果
+ Addition 10 + 3 13
- Subtraction 10 - 3 7
* Multiplication 10 * 3 30
/ Division 10 / 3 3 (整數除法)
% 模數(剩餘數) 10 % 3 1

你可以自己用 C# 程式碼編輯器執行這段程式碼。

理解模數(%)

模算符 % 會回傳除法後剩餘的部分。 有助於檢查某個數是否可被整除:

Console.WriteLine(10 % 2);   // Output: 0 (10 is even)
Console.WriteLine(11 % 2);   // Output: 1 (11 is odd)

運算順序

C# 遵循標準數學運算順序(PEMDAS):括號,接乘除法,再加減法。 請用括號控制順序:

int standard = 2 + 3 * 4;      // Multiplication first: 14
int forced = (2 + 3) * 4;      // Parentheses first: 20

複合指派運算子

一個常見的模式是使用變數本身的值來更新變數——例如加分數或從餘額中扣除。 C# 對此有簡寫形式的運算子:

int score = 50;
score = score + 10;    // Standard way: score is 60
score += 10;           // Shorthand: score is 70

同樣的簡寫法適用於其他操作:

Operator Meaning 範例 結果(從 10 開始)
+= 新增並指派 x += 5 15
-= 減並指派 x -= 5 5
*= 乘並指派 x *= 5 50
/= 分割並指派 x /= 5 2

遞增和遞減運算子

對於加減 1,C# 的運算子甚至更短——++ 和 --:

int count = 5;
count++;                       // Same as count = count + 1
Console.WriteLine(count);      // Output: 6

count--;                       // Same as count = count - 1
Console.WriteLine(count);      // Output: 5

位置很重要:前置遞增與後置遞增

和 運算子的行為會因其出現在變數--或++而有所不同:

  • 後置遞增(value++):先使用目前值,再遞增
  • 預遞增 (++value):先進行遞增,然後使用新值
int a = 5;
Console.WriteLine(a++);   // Output: 5 (uses old value, then increments)
Console.WriteLine(a);     // Output: 6 (a was incremented)

int b = 5;
Console.WriteLine(++b);   // Output: 6 (increments first, then uses new value)
Console.WriteLine(b);     // Output: 6

同樣的規則也適用於 -- (遞減)。

整數除法與小數法

當你除以兩個整數時,C# 會截斷(刪除)小數部分:

int result = 7 / 2;
Console.WriteLine(result);     // Output: 3 (not 3.5)

為了保留小數,至少有一個數字必須是十進位類型:

decimal result = 7m / 2m;
Console.WriteLine(result);     // Output: 3.5

這就是為什麼選擇合適的資料型態對計算很重要。 下一節,你會學習在需要時如何轉換類型。