算术运算符(C# 参考)Arithmetic operators (C# reference)

以下运算符对数值类型执行算术运算:The following operators perform arithmetic operations with numeric types:

这些运算符支持所有整型浮动数值类型。Those operators support all integral and floating-point numeric types.

增量运算符 ++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 unary - operator doesn't support the ulong type.

乘法运算符 *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 implicit conversions between numeric types, see Implicit numeric conversions table.

余数运算符 %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 differs from the IEEE 754. 如果需要符合 IEEE 754 的余数运算,使用 Math.IEEERemainder 方法。If you need the remainder operation that complies with the IEEE 754, 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 also can 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 also can use the - operator for delegate removal. 有关详细信息,请参阅-运算符一文。For more information, see the - operator 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 是预定义的运算符并且运算的结果可以显式转换为 x 的类型 T,则形式为 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 events. 有关详细信息,请参阅如何:订阅和取消订阅事件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 C# operators.

算术溢出和被零除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.

在整数算术溢出的情况下,溢出检查上下文(可能已检查或未检查)将控制引发的行为:In case of integer arithmetic overflow, an overflow checking context, which can be checked or unchecked, controls the resulting behavior:

  • 在已检查的上下文中,如果在常数表达式中发生溢出,则会发生编译时错误。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.
  • 在未检查的上下文中,会通过丢弃任何不适应目标类型的高序位来将结果截断。In an unchecked context, the result is truncated by discarding any high-order bits that don't fit in the destination type.

在使用已检查和未检查的语句时,可以使用 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, the 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.DoubleSystem.SingleSystem.Decimal 参考页面上的注解。For more information, see remarks at System.Double, System.Single, or System.Decimal reference pages.

运算符可重载性Operator overloadability

用户定义类型可以重载一元(++--+-)和二元(*/%+-)算术运算符。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