C# Programming Operator precedence

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
7 replies · 2K views
SherlockOhms
Messages
309
Reaction score
0

Homework Statement


What is the value of x = 5 + (9 * 5) * (3 ^ 3/2 - 20).

Homework Equations


Operator precedence.

The Attempt at a Solution


x = 5 + (45) * (3 ^ 3/2 - 20).
Is the "^" here the exclusive or operator? In that case wouldn't x have 2 possible values?
 
Last edited:
Physics news on Phys.org
SteamKing said:
Looks like a plus to me. Check your post for typos. I see at least two.

Anywho, aren't XOR operators and such bitwise operators rather than arithmetic operators?

Edited it there. No, I'm not referring to the plus sign above. I'm literally asking about this "^" sign. The XOR operator. I thought they were only used in boolean comparisons and stuff.
 
The ^ operator in C# is defined for pairs of integral arguments (int, uint, long, ulong), pairs of args of some enumerated type, and pairs of type bool. For an expression consisting of int constants, like yours, ^ computes the bitwise logical exclusive OR of the two operands.

Keep in mind the relative precedence of the operators in your expression: * and / are higher than + and -, which are higher than any of the logical operators.
 
Also keep in mind that most C/C++ compilers do automatic typecasting, so you may THINK you have one kind of variable after an operation, but you really have another kind. For example, depending on what operation is performed on it, the term

3/2

might reduce to an integer (1) or to a single (1.5). I think the term by itself reduces to 1 because both parts are integer so the compiler will assume you want an integer answer (unless you set a = 3/2 and a is a single. Anyway that kind of thing is important to keep in mind, and to understand how your compiler handles it.
 
Thanks for the help lads. So, what exactly should the output be? An I right in assuming there'll be 2 possible values for x? It was actually an exam question and not a homework question so I'm just wondering out of pure curiosity like.
 
x ends up as -805. The tricky part is evaluating 3^(-19), which entails writing -19 as a binary number so you can calculate the XOR with 3.
 
Ohh, ok. I see. Thanks for that man.