|
|
|
|
|
|
Changing English Statements into Logical Expressions |
|
|
|
|
|
|
|
|
|
In most cases, you can write a logical expression directly from an English statement or mathematical term in an algorithm. But you have to watch out for some tricky situations. Remember our sample logical expression: |
|
|
|
|
|
|
|
|
|
midtermGrade == A || finalGrade == A |
|
|
|
|
|
|
|
|
|
In English, you would be tempted to write this expression: Midterm grade or final grade equals A. In C++, you can't write the expression as you would in English. That is, |
|
|
|
|
|
|
|
|
|
midtermGrade || finalGrade == A |
|
|
|
|
|
|
|
|
|
won't work because the || operator is connecting a char value (midtermGrade) and a logical expression (finalGrade == A). The two operands of || should be logical expressions. (Note that this expression is wrong in terms of logic, but it isn't wrong to the C++ compiler. Recall that the || operator may legally connect two expressions of any data type, so this example won't generate a syntax error message. The program will run, but it won't work the way you intended.) |
|
|
|
|
|
|
|
|
|
A variation of this mistake is to express the English assertion i equals either 3 or 4 as |
|
|
|
|
|
|
|
|
|
|
Again, the syntax is correct but the semantics are not. This expression always evaluates to TRUE. The first subexpression, i == 3, may be TRUE or FALSE. But the second subexpression, 4, is nonzero (TRUE). Therefore, the || operation causes the entire expression to be TRUE. We repeat: Use the || operator (and the && operator) only to connect two logical expressions. Here's what we want: |
|
|
|
|
|
|
|
|
|
|
In math books, you might see a notation like this: |
|
|
|
|
|
|
|
|
|
|
which means y is between 12 and 24. This expression is legal in C++ but gives an unexpected result. First, the relation 12<y is evaluated, giving the int result 1 (TRUE) or 0 |
|
|
|
|