Operator precedence in C#
Is
(int)(int1 / (float)var2.Count() * 100)
equivalent to
(int)((int1 / (float)var2.Count()) * 100)
...and will it use floating point or integer division?
Edit... if the answer is yes to the above, what is the advantage of performing a floating point 开发者_开发技巧division here?
/
and *
have the same operator precedence, under §7.2.1 so the two results should be the same (using float
rules).
I, however, can't be bothered to learn precedence tables; I just use brackets. Then it works in any language without needing to remember it.
Another important question is the rounding in the final (int)
cast: do you expect that to be "up", "down" or "bankers"?
Precedence rules are really annoying to remember, so I too prefer to use brackets to disambiguate. I try to follow the advice to "write code for people first, computers second". But, there's an interesting mnemonic (that I learned from Bruce Eckel's books) to remember (some of) the rules: "Ulcer Addicts Really Like C A lot":
Ulcer - Unary (+, -, ++, --, !)
Addicts - Arithmetic (and shift) (+, -, *, /, %, <<, >>)
Really - Relational (<, >, ==, <=, >=, !=)
Like - Logical (and bitwise) (&&, ||, &, |, ^)
C - Conditional ( ? : ) <- this is the conditional ternary operator
A lot - Assignment ( =, *=, +=, ...)
It's not perfect, bitwise operators are squeezed in and we have to know that multiplication operators (*, /, %) take precedence over addition ones (+, -).
They are equivalent and it will use floating point division. Even if the multiplication happened first, floating point division would be used since the int is divided by the result of float*int which is float.
Edit:
If the answer is yes to the above, what is the advantage of performing a floating point division here?
Is it an advantage? The first thing that you should be considering is whether or not it's correct since the result will be different. Judging by the code it seems you are trying to calculate some percentage. When using integer divison, if "int1" is always smaller than var2.Count() the result will always be 0 which might not be what you want.
I would say Yes, division and multiplication should go left-to-right. And thus it is a float division.
PS: replace float
with double
wherever you can.
See the C# Language Specification: Operator precedence and associativity.
It's the same. Both will use float division.
yes both are equivalent.
Both will use floating point division.
Integer division will only give back the whole part of the answer i.e. 3/2 will be 1 whereas float division will give you 1.5
精彩评论