Exercises 3.1
- For each legal expression, state its value. For each illegal expression,
state the reason that it is illegal.
- (2 + (-5)) != 3
- 'm' < = 'p'
- 'Q' == 'q'
- '*' < '*'
- 8. 23 =< 8. 2300
- (7 / 3) = 2
- false == 0
- (25 % 4) >= 1
State, with reasons, what this program will print.
class BooleanVariables
{
public static void main (String[] args)
{
boolean perhaps, maybe;
perhaps = 4 < 5;
maybe = -17 % 4 == 1;
System.out.println("perhaps: " + perhaps);
System.out.println("maybe : " + maybe);
}
}
For each expression, state whether it is true or false.
- 'q' < 'm'
- 'G' > 'K'
- 'a' < 'Z'
- '5' < 'v'
- 'q' > '7'
- '9' < ' '
- 'X' < 's'
- 'i' < 'I'
Determine the value of each expression.
- 7 / 3 < 17 / 3.0
- 'F' > 'B' + 3
- -6 % 3 < 0
- (int)1.1 * 0.9 <= 0
- (2 + 3 < 6) == true
- (2 * 3 < 5) != true
Because of the ways that Java's floating point values are stored, it
may happen that numbers which should, in theory, be equal are, in
fact, only approximately equal. Thus, it is not a good idea to test
for exact equality of two floating point values. A better idea is to see
if the numbers differ by less than some desired value. For example,
given two double values x and y, the expression
Math.abs(x - y) < Math.abs(1e-3 * x)
will be true if and only if x and y differ by no more than l/1000th of
the value of x.
(a) Write an expression that will be true if and only if x and y differ
by no more than one one-millionth of the value of x.
(b) Why is it a good idea to have the test dependent on the magnitude
of one of the values being compared?
| |