Introduction to Computer Science

Start Lecture #5

Homework: The problems from lecture 4 that weren't assigned (3.7 and 3.9).

3.9 (Alternate): A Yet Better Quadratic Solver

Let's fix two problems with our previous solution to solving the quadratic equation Ax2+Bx+C=0.

  1. We shamefully divided by 2A without checking if A==0. In that case we don't have a quadratic equation at all.
  2. After we determine that the discriminant is negative, we need not check if it is zero or if it is positive.

Let's do this in class; one possible solution is here.

3.10: Problem: Computing the Body Mass Index

Read.

3.11: Problem: Computing Taxes

Let's do this one in class. Handout sheet with tax table. A scan of the table is here.

3.12: Logical Operators

Boolean Operators
OperatorName


!not
&&and
||or
^exclusive or

Like most computer languages, Java permits Boolean expressions to contain so-called "logical operators". These operators have Boolean expressions as both operands and results.

The table on the right shows the four possibilities. The not operator is unary (takes one operand) and returns the opposite Boolean value as result.

The and operator is binary and returns false unless when both operands are true.

The (inclusive) or operator is binary and returns true unless both operands are false. That is, the meaning of || is one or the other or both.

The exclusive or operator is binary and returns true if and only if exactly one operand is true. That is, the meaning of ^ is one or the other but not both.

3.13: Problem: Determining Leap Year

As you know a day is the time it takes the earth to rotate about its axis, and a year is the time it takes for the earth to revolve around the sun.

By these definitions a year is a little less than 365.25 days. To keep the calendars correct (meaning that, e.g., the vernal equinox occurs around the same time each year), most years have 365 days, but some have 366.

A very good approximation, which will work up to at least the year 4000 and likely much further is as follows (surprisingly, we are not able to predict exactly when the vernal equinox will occur far in the future; see wikipedia).

Let's write in class a program that asks for the year and replies by saying if the year is a leap year. One solution is in the book.

3.14: Problem: Lottery

The book has an interesting lottery game. The program generates a random 2-digit number and accepts another 2-digit number from the user.

We will write this in class, but need a new library method from Java, Math.random returns a random number between 0 and 1. The value returned, a double, might be 0, but will not be 1.

One solution is in the book.