Книга: C# 2008 Programmer

Operator Precedence

Operator Precedence

When you use multiple operators in the same statement, you need be aware of the precedence of each operator (that is, which operator will evaluate first). The following table shows the various C# operators grouped in the order of precedence. Operators within the same group have equal precedence (operators include some keywords).

Category Operators
Primary x.y f(x) a[x] x++ x-- new typeof checked unchecked
Unary + - ! ~ ++x --x (T)x
Multiplicative * / %
Additive + -
Shift << >>
Relational and type testing < > <= >> is as
Equality == !=
Logical AND &
Logical XOR ^
Logical OR |
Conditional AND &&
Conditional OR ||
Conditional ?:
Assignment = *= /= %= += -= <<= >>= &= ^= | =

When you are in doubt of the precedence of two operators, always use parentheses to force the compiler to evaluate the expression first. For example, the formula to convert a temperature from Fahrenheit to Celsius is:

Tc = (5/9)*(Tf-32);

When implemented in C#, the formula looks like this:

double fahrenheit = 100;
double celcius = 5.0 / 9.0 * fahrenheit - 32;
Console.WriteLine("{0:##.##} degrees C",celcius); //---23.56 degrees C---

But this produces a wrong answer because 5.0 / 9.0 and fahrenheit - 32 must be evaluated separately before their results are multiplied to get the final answer. What's happened is that, according to the precedence table, 5.0 / 9.0 * fahrenheit is evaluated first and then 32 is subtracted from the result. This gives the incorrect answer of 23.56 degrees C.

To correct this, you use parentheses to group all the expressions that need to be evaluated first, like this:

double fahrenheit = 100;
double celcius = (5.0 / 9.0) * (fahrenheit - 32);
Console.WriteLine("{0:##.##} degrees C",celcius); //---37.78 degrees C---

This code gives the correct answer of 37.78 degrees C.

Оглавление книги


Генерация: 1.052. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз