|
course.wilkes.edu/CS125Labs |
||||||||
Experiment 5: Logical Expressions
It is sometimes useful to be able to combine relational expressions.
For example, suppose we wish to find out if the value of 1 <= x <= 100However, C++ is not Mathematics: if you try this and x is negative,
express.cpp, try it and see for yourself!
Simply writing mathematical expressions in C++ can thus give incorrect answers.
To do this sort of thing in C++, what is needed is to join the two relational expressions 1 <= xand x <= 100using one of the logical operators. These operators include:
The AND and OR operators each require two operands.
A third logical operator is the NOT operator ( To solve the problem mentioned above, we can use the AND operator: 1 <= x && x <= 100For this problem, we could have instead used the OR operator: 1 > x || x > 100and still achieved the correct result. Try one of these in express.cpp,
and verify that it gives you the correct
result for both positive and negative values.
Now it is your turn: in the space below, write a logical expression
using the AND operator
that produces the value true if the value of
Then rewrite your logical expression using the OR operator
(and different relational operators)
so that it produces the same results.
(Hint: Use the NOT operator.)
As before, test that it is correct using
Relational expressions and logical expressions both produce
Boolean expressions have a variety of uses.
One of these is the
#include <cassert> // above main
// ...
cin >> x; // within main
assert(x != 0);
Once the user enters a value for x,
the assert() mechanism will evaluate the boolean expression within
the parentheses.
If that boolean expression is true, execution will continue as usual;
but if the boolean expression is false, the program will terminate
and a diagnostic message will be displayed,
listing the precondition that failed (i.e., was false).
Try this in express.cpp, and in the space below,
record the diagnostic message that is displayed when your precondition fails:
You should now know about the logical operators, and how they can be
used to combine relational expressions into
arbitrarily complex boolean expressions.
You should also know about how preconditions can be expressed
as boolean expressions, and how the
|
Home Membership
|
|||||||
|
Last update: Tuesday, August 22, 2000 at 11:31:59 AM. |
||||||||