算術運算子 (C# 參考)Arithmetic operators (C# reference)

下列運算子會使用數數值型別的運算元來執行算數運算:The following operators perform arithmetic operations with operands of numeric types:

所有整數浮點數數值型別都支援這些運算子。Those operators are supported by all integral and floating-point numeric types.

在整數類資料類型的情況下,這些運算子 (除了 ++-- 運算子之外,) 是針對 intuintlongulong 類型而定義的。In the case of integral types, those operators (except the ++ and -- operators) are defined for the int, uint, long, and ulong types. 當運算元屬於其他整數類型 (sbytebyteshortushort 或) 時 char ,其值會轉換成 int 類型,也就是運算的結果類型。When operands are of other integral types (sbyte, byte, short, ushort, or char), their values are converted to the int type, which is also the result type of an operation. 當運算元的整數或浮點數類型不同時,如果類型存在,它們的值會轉換成最接近的包含類型。When operands are of different integral or floating-point types, their values are converted to the closest containing type, if such a type exists. 如需詳細資訊,請參閱 C# 語言規格數值升階一節。For more information, see the Numeric promotions section of the C# language specification. ++-- 運算子是針對所有整數和浮點數類型和char類型所定義。The ++ and -- operators are defined for all integral and floating-point numeric types and the char type.

遞增運算子 ++Increment operator ++

一元遞增運算子 ++ 的運算元遞增量為 1。The unary increment operator ++ increments its operand by 1. 運算元必須是變數、屬性存取或索引子存取。The operand must be a variable, a property access, or an indexer access.

遞增運算子支援兩種形式:後置遞增運算子 x++ 和前置遞增運算子 ++xThe increment operator is supported in two forms: the postfix increment operator, x++, and the prefix increment operator, ++x.

後置遞增運算子Postfix increment operator

x++ 的結果為運算「之前」 ** 的 x 值,如下列範例所示:The result of x++ is the value of x before the operation, as the following example shows:

int i = 3;
Console.WriteLine(i);   // output: 3
Console.WriteLine(i++); // output: 3
Console.WriteLine(i);   // output: 4

前置遞增運算子Prefix increment operator

++x 的結果為運算「之後」 ** 的 x 值,如下列範例所示:The result of ++x is the value of x after the operation, as the following example shows:

double a = 1.5;
Console.WriteLine(a);   // output: 1.5
Console.WriteLine(++a); // output: 2.5
Console.WriteLine(a);   // output: 2.5

遞減運算子 --Decrement operator --

一元遞減運算子 (--) 的運算元遞減量為 1。The unary decrement operator -- decrements its operand by 1. 運算元必須是變數、屬性存取或索引子存取。The operand must be a variable, a property access, or an indexer access.

遞減運算子支援兩種形式:後置遞減運算子 x-- 和前置遞減運算子 --xThe decrement operator is supported in two forms: the postfix decrement operator, x--, and the prefix decrement operator, --x.

後置遞減運算子Postfix decrement operator

x-- 的結果為運算「之前」 ** 的 x 值,如下列範例所示:The result of x-- is the value of x before the operation, as the following example shows:

int i = 3;
Console.WriteLine(i);   // output: 3
Console.WriteLine(i--); // output: 3
Console.WriteLine(i);   // output: 2

前置遞減運算子Prefix decrement operator

--x 的結果為運算「之後」 ** 的 x 值,如下列範例所示:The result of --x is the value of x after the operation, as the following example shows:

double a = 1.5;
Console.WriteLine(a);   // output: 1.5
Console.WriteLine(--a); // output: 0.5
Console.WriteLine(a);   // output: 0.5

一元加號和減號運算子Unary plus and minus operators

一元 + 運算子會傳回其運算元的值。The unary + operator returns the value of its operand. 一元 - 運算子會計算其運算元的負數值。The unary - operator computes the numeric negation of its operand.

Console.WriteLine(+4);     // output: 4

Console.WriteLine(-4);     // output: -4
Console.WriteLine(-(-4));  // output: 4

uint a = 5;
var b = -a;
Console.WriteLine(b);            // output: -5
Console.WriteLine(b.GetType());  // output: System.Int64

Console.WriteLine(-double.NaN);  // output: NaN

Ulong型別不支援一元 - 運算子。The ulong type doesn't support the unary - operator.

乘法運算子 *Multiplication operator *

乘法運算子 * 會計算其運算元的乘積:The multiplication operator * computes the product of its operands:

Console.WriteLine(5 * 2);         // output: 10
Console.WriteLine(0.5 * 2.5);     // output: 1.25
Console.WriteLine(0.1m * 23.4m);  // output: 2.34

一元 * 運算子是一個指標間接運算子The unary * operator is the pointer indirection operator.

除法運算子 /Division operator /

除法運算子 / 會將它的左邊運算元除以右邊運算元。The division operator / divides its left-hand operand by its right-hand operand.

整數除數Integer division

針對整數型別的運算元,/ 運算子的結果會是整數型別,且等於兩個運算元捨入為零的商:For the operands of integer types, the result of the / operator is of an integer type and equals the quotient of the two operands rounded towards zero:

Console.WriteLine(13 / 5);    // output: 2
Console.WriteLine(-13 / 5);   // output: -2
Console.WriteLine(13 / -5);   // output: -2
Console.WriteLine(-13 / -5);  // output: 2

若要以浮點數的形式取得兩個運算元的商,請使用 floatdoubledecimal 型別:To obtain the quotient of the two operands as a floating-point number, use the float, double, or decimal type:

Console.WriteLine(13 / 5.0);       // output: 2.6

int a = 13;
int b = 5;
Console.WriteLine((double)a / b);  // output: 2.6

浮點除數Floating-point division

針對 floatdoubledecimal 型別,/ 運算子的結果會是兩個運算元的商:For the float, double, and decimal types, the result of the / operator is the quotient of the two operands:

Console.WriteLine(16.8f / 4.1f);   // output: 4.097561
Console.WriteLine(16.8d / 4.1d);   // output: 4.09756097560976
Console.WriteLine(16.8m / 4.1m);   // output: 4.0975609756097560975609756098

如果其中一個運算元是 decimal,則另一個運算元便不可以是 floatdouble,因為 floatdouble 都無法隱含轉換為 decimalIf one of the operands is decimal, another operand can be neither float nor double, because neither float nor double is implicitly convertible to decimal. 您必須明確地將 floatdouble 運算元轉換為 decimal 型別。You must explicitly convert the float or double operand to the decimal type. 如需有關數數值型別之間轉換的詳細資訊,請參閱內建數值轉換For more information about conversions between numeric types, see Built-in numeric conversions.

餘數運算子 %Remainder operator %

餘數運算子 % 會計算其左邊運算元除以右邊運算元之後的餘數。The remainder operator % computes the remainder after dividing its left-hand operand by its right-hand operand.

整數餘數Integer remainder

對整數型別的運算元來說,a % b 的結果是 a - (a / b) * b 所產生的值。For the operands of integer types, the result of a % b is the value produced by a - (a / b) * b. 非零餘數的正負號與左邊運算元的正負號相同,如下列範例所示:The sign of the non-zero remainder is the same as that of the left-hand operand, as the following example shows:

Console.WriteLine(5 % 4);   // output: 1
Console.WriteLine(5 % -4);  // output: 1
Console.WriteLine(-5 % 4);  // output: -1
Console.WriteLine(-5 % -4); // output: -1

使用 Math.DivRem 方法計算整數除法和餘數結果。Use the Math.DivRem method to compute both integer division and remainder results.

浮點數餘數Floating-point remainder

對於 floatdouble 運算元,有限 xyx % y 結果是 z 值,像是For the float and double operands, the result of x % y for the finite x and y is the value z such that

  • z 不是零,其正負號與 x 的正負號相同。The sign of z, if non-zero, is the same as the sign of x.
  • z 的絕對值是由 |x| - n * |y| 產生的值,其中 n 為最大可能整數,小於或等於 |x| / |y|,而 |x||y|則分別是 xy 的絕對值。The absolute value of z is the value produced by |x| - n * |y| where n is the largest possible integer that is less than or equal to |x| / |y| and |x| and |y| are the absolute values of x and y, respectively.

注意

這種計算餘數的方法類似于用於整數運算元的,但與 IEEE 754 規格不同。This method of computing the remainder is analogous to that used for integer operands, but different from the IEEE 754 specification. 如果您需要符合 IEEE 754 規格的餘數運算,請使用 Math.IEEERemainder 方法。If you need the remainder operation that complies with the IEEE 754 specification, use the Math.IEEERemainder method.

如需在非有限運算元情況中 % 運算子的行為,請參閱 C# 語言規格餘數運算子小節。For information about the behavior of the % operator with non-finite operands, see the Remainder operator section of the C# language specification.

針對 decimal 運算元,餘數運算子 % 相當於 System.Decimal 型別的餘數運算子For the decimal operands, the remainder operator % is equivalent to the remainder operator of the System.Decimal type.

下列範例示範具有浮點運算元的餘數運算子行為:The following example demonstrates the behavior of the remainder operator with floating-point operands:

Console.WriteLine(-5.2f % 2.0f); // output: -1.2
Console.WriteLine(5.9 % 3.1);    // output: 2.8
Console.WriteLine(5.9m % 3.1m);  // output: 2.8

加法運算子 +Addition operator +

加法運算子 + 會計算其運算元的總和:The addition operator + computes the sum of its operands:

Console.WriteLine(5 + 4);       // output: 9
Console.WriteLine(5 + 4.3);     // output: 9.3
Console.WriteLine(5.1m + 4.2m); // output: 9.3

您也可以使用 + 運算子進行字串串連和委派組合。You can also use the + operator for string concatenation and delegate combination. 如需詳細資訊,請參閱 ++= 運算子一文。For more information, see the + and += operators article.

減法運算子 -Subtraction operator -

減法運算子 - 會從左邊運算元減去右邊運算元:The subtraction operator - subtracts its right-hand operand from its left-hand operand:

Console.WriteLine(47 - 3);      // output: 44
Console.WriteLine(5 - 4.3);     // output: 0.7
Console.WriteLine(7.5m - 2.3m); // output: 5.2

您也可以使用 - 運算子來移除委派。You can also use the - operator for delegate removal. 如需詳細資訊,請參閱 --= 運算子一文。For more information, see the - and -= operators article.

複合指派Compound assignment

若是二元運算子 op,表單的複合指派運算式For a binary operator op, a compound assignment expression of the form

x op= y

相當於is equivalent to

x = x op y

但只會評估 x 一次。except that x is only evaluated once.

下列範例示範如何搭配算術運算子使用複合指派:The following example demonstrates the usage of compound assignment with arithmetic operators:

int a = 5;
a += 9;
Console.WriteLine(a);  // output: 14

a -= 4;
Console.WriteLine(a);  // output: 10

a *= 2;
Console.WriteLine(a);  // output: 20

a /= 4;
Console.WriteLine(a);  // output: 5

a %= 3;
Console.WriteLine(a);  // output: 2

由於數值升階的緣故,op 作業結果可能無法隱含轉換成 xT 型別。Because of numeric promotions, the result of the op operation might be not implicitly convertible to the type T of x. 在此情況下,如果 op 是預先定義的運算子,且作業結果可以明確轉換成 xT 型別,則形式 x op= y 的複合指派運算式相等於 x = (T)(x op y),唯一的不同在於 x 只會評估一次。In such a case, if op is a predefined operator and the result of the operation is explicitly convertible to the type T of x, a compound assignment expression of the form x op= y is equivalent to x = (T)(x op y), except that x is only evaluated once. 下列範例示範了該行為:The following example demonstrates that behavior:

byte a = 200;
byte b = 100;

var c = a + b;
Console.WriteLine(c.GetType());  // output: System.Int32
Console.WriteLine(c);  // output: 300

a += b;
Console.WriteLine(a);  // output: 44

您也可以使用 +=-= 運算子,分別訂閱和取消訂閱事件You also use the += and -= operators to subscribe to and unsubscribe from an event, respectively. 如需詳細資訊,請參閱如何訂閱及取消訂閱事件For more information, see How to subscribe to and unsubscribe from events.

運算子優先順序和關聯性Operator precedence and associativity

下列清單會將算術運算子從最高優先順序開始排序到最低優先順序:The following list orders arithmetic operators starting from the highest precedence to the lowest:

  • 後置遞增 x++ 和遞減 x-- 運算子Postfix increment x++ and decrement x-- operators
  • 前置遞增 ++x 和遞減 --x 以及一元 +- 運算子Prefix increment ++x and decrement --x and unary + and - operators
  • 乘法類 */% 運算子Multiplicative *, /, and % operators
  • 加法類 +- 運算子Additive + and - operators

二元算術運算子都是左向關聯。Binary arithmetic operators are left-associative. 亦即,具有相同優先順序層級的運算子會由左至右進行評估。That is, operators with the same precedence level are evaluated from left to right.

使用括號 () 變更運算子優先順序和關聯性強制執行的評估順序。Use parentheses, (), to change the order of evaluation imposed by operator precedence and associativity.

Console.WriteLine(2 + 2 * 2);   // output: 6
Console.WriteLine((2 + 2) * 2); // output: 8

Console.WriteLine(9 / 5 / 2);   // output: 0
Console.WriteLine(9 / (5 / 2)); // output: 4

如需依優先順序層級排序之 c # 運算子的完整清單,請參閱c # 運算子一文的運算子優先順序一節。For the complete list of C# operators ordered by precedence level, see the Operator precedence section of the C# operators article.

算術溢位和除數為零Arithmetic overflow and division by zero

當算術運算的結果超出可能相關數字型別有限值的範圍之外時,算術運算子的行為取決於其運算元的型別。When the result of an arithmetic operation is outside the range of possible finite values of the involved numeric type, the behavior of an arithmetic operator depends on the type of its operands.

整數算術溢位Integer arithmetic overflow

整數除以零一定會擲回 DivideByZeroExceptionInteger division by zero always throws a DivideByZeroException.

如果整數算術溢位,則溢位檢查內容 (可以是 checked 或 unchecked) 可控制所產生的行為:In case of integer arithmetic overflow, an overflow checking context, which can be checked or unchecked, controls the resulting behavior:

  • 在 checked 內容中,如果常數運算式發生溢位,則會發生編譯時期錯誤。In a checked context, if overflow happens in a constant expression, a compile-time error occurs. 否則,當運算是在執行階段執行時,就會擲回 OverflowExceptionOtherwise, when the operation is performed at run time, an OverflowException is thrown.
  • 在 unchecked 內容中,會捨棄目的型別不適用的高序位位元,以便將結果截斷。In an unchecked context, the result is truncated by discarding any high-order bits that don't fit in the destination type.

除了 checked 與 unchecked 陳述式之外,您還可以使用 checkedunchecked 運算子控制評估運算式的溢位檢查內容:Along with the checked and unchecked statements, you can use the checked and unchecked operators to control the overflow checking context, in which an expression is evaluated:

int a = int.MaxValue;
int b = 3;

Console.WriteLine(unchecked(a + b));  // output: -2147483646
try
{
    int d = checked(a + b);
}
catch(OverflowException)
{
    Console.WriteLine($"Overflow occurred when adding {a} to {b}.");
}

根據預設,unchecked 內容中會發生算術運算。By default, arithmetic operations occur in an unchecked context.

浮點算術溢位Floating-point arithmetic overflow

具有 floatdouble 型別的算術運算永遠不會擲回例外狀況。Arithmetic operations with the float and double types never throw an exception. 具有這些型別之算術運算的結果可以是代表無限值和非數字的其中一個特殊值:The result of arithmetic operations with those types can be one of special values that represent infinity and not-a-number:

double a = 1.0 / 0.0;
Console.WriteLine(a);                    // output: Infinity
Console.WriteLine(double.IsInfinity(a)); // output: True

Console.WriteLine(double.MaxValue + double.MaxValue); // output: Infinity

double b = 0.0 / 0.0;
Console.WriteLine(b);                // output: NaN
Console.WriteLine(double.IsNaN(b));  // output: True

若是 decimal 型別的運算元,算術溢位一律會擲回 OverflowException,且除數為零一定會擲回 DivideByZeroExceptionFor the operands of the decimal type, arithmetic overflow always throws an OverflowException and division by zero always throws a DivideByZeroException.

四捨五入錯誤Round-off errors

由於實數和浮點算術的浮點標記法有一般限制,因此在具有浮點類型的計算中可能會發生四捨五入錯誤。Because of general limitations of the floating-point representation of real numbers and floating-point arithmetic, round-off errors might occur in calculations with floating-point types. 亦即,運算式產生的結果可能不同於預期的數學結果。That is, the produced result of an expression might differ from the expected mathematical result. 下列範例將示範幾個這類案例:The following example demonstrates several such cases:

Console.WriteLine(.41f % .2f); // output: 0.00999999

double a = 0.1;
double b = 3 * a;
Console.WriteLine(b == 0.3);   // output: False
Console.WriteLine(b - 0.3);    // output: 5.55111512312578E-17

decimal c = 1 / 3.0m;
decimal d = 3 * c;
Console.WriteLine(d == 1.0m);  // output: False
Console.WriteLine(d);          // output: 0.9999999999999999999999999999

如需詳細資訊,請參閱system. Double 、system.web 或system.string 參考頁面上System.Decimal的備註。For more information, see remarks at the System.Double, System.Single, or System.Decimal reference pages.

運算子是否可多載Operator overloadability

使用者定義型別可以多載一元 (++--+-) 和 binary (、、 */ % +-) 算術運算子。A user-defined type can overload the unary (++, --, +, and -) and binary (*, /, %, +, and -) arithmetic operators. 當二元運算子多載時,對應的複合指派運算子也會隱含地多載。When a binary operator is overloaded, the corresponding compound assignment operator is also implicitly overloaded. 使用者定義型別無法明確地多載複合指派運算子。A user-defined type cannot explicitly overload a compound assignment operator.

C# 語言規格C# language specification

如需詳細資訊,請參閱 C# 語言規格的下列幾節:For more information, see the following sections of the C# language specification:

另請參閱See also