简体   繁体   中英

How do I solve this logical operator problem?

My professor gave us a logical operator worksheet from my C++ clas and I got stumped on this problem. If x = -2, y = 5, z = 0, and t = -4, what is the value of each of the following logical expressions?

3 * y / 4 < 8 && y >= 4

I get stuck on this step after I plug everything in. 3 < 8 && 5

I know that on the left 3 * 5= 15, and 15 / 4 = 3. Now the other side is where I get stuck at. I know 5 is true since it's greater than or equal to 4. But I don't know what to do with next when its 8 && 5. Can anyone help?

You can put parenthesis around the various sub-expressions in your expression by following the order of precedence of operators and their associativity .

3 * y / 4 < 8 && y >= 4

is

(3 * y) / 4 < 8 && y >= 4

is

((3 * y) / 4) < 8 && y >= 4

is

(((3 * y) / 4) < 8) && y >= 4

is

(((3 * y) / 4) < 8) && (y >= 4)

That should give you a clear guideline of what the expression should evaluate to.

This seems to be an exercise in operator precedence. When precedence is taken into account, the statement 3 * y / 4 < 8 && y >= 4 is equivalent with

(((3 * y) / 4) < 8) && (y >= 4)

Substituting the variables, we have

(((3 * 5) / 4) < 8 && (5 >= 4)

After doing the math, we end up with

(3 < 8) && (5 >= 4)

3 is indeed lesser than 8, and 5 is indeed greater or equal than 4, so both sides of boolean and are true, and the whole expression is evaluated to true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM