问题
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?
回答1:
/
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"?
回答2:
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 (+, -).
回答3:
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.
回答4:
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.
回答5:
See the C# Language Specification: Operator precedence and associativity.
回答6:
It's the same. Both will use float division.
回答7:
yes both are equivalent.
Both will use floating point division.
回答8:
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
来源:https://stackoverflow.com/questions/3280039/operator-precedence-in-c-sharp