Practice Program 6.1:

! Your are asked to calculate the roots of the equation

! a*x^2 + b*x + c = 0 .

! Recall that the roots are given by the expressions

! x1 = (-b+sqr(b*b-4*a*c))/(2*a)

! x2 = (-b-sqr(b*b-4*a*c))/(2*a) .

 

! You write the following program:

 

! Program with a logical error.

 

!INPUT prompt "Value of a? ": a

!INPUT prompt "Value of b? ": b

!INPUT prompt "Value of c? ": c

!LET x1 = (-b+sqr(b*b - 4*a*c))/(2*a)

!LET x2 = (-b-sqr(b*b - 4*a*c))/(2*a)

!PRINT "The roots are"; x1; "and ";x2

!END

 

! This program works when the roots are real; for example,

! substituting a=1,b=0,c=-4 gives roots 2 and -2.

! However, a=1,b=0,c=+4

! gives an error message sqr of negative number.

 

! Pseudocode: rewrite the program to trap the error and permit

! the user to enter a new set of numbers a,b,c.

! The syntax for trapping errors is:

! WHEN exception in

! PROTECTED block (in this case our calculation of roots)

! USE

! EXCEPTION handler block (ask user for new a,b,c entry in a loop)

! END WHEN

 

LET noerror$="false"

DO

LET x1=0

LET x2=0

INPUT prompt "Value of a? ": a

INPUT prompt "Value of b? ": b

INPUT prompt "Value of c? ": c

 

WHEN exception in

 

! protected block begin

 

LET x1 = (-b+sqr(b*b - 4*a*c))/(2*a)

LET x2 = (-b-sqr(b*b - 4*a*c))/(2*a)

 

PRINT "The roots are "; x1; "and ";x2

LET noerror$="true"

 

! protected block end

USE

!exception handler block begin

IF extype=3005 then

PRINT "Unexpected error: ";extext$;" ";"Type=";extype

ELSE

PRINT "Really unexpected error: "; extext$;"Type=";extype

END IF

PRINT "Please try again."

!exception handler block end

END WHEN

LOOP until noerror$="true"

END

 

! A user enters a value of 3 for a, 2 for b, and 2 for c. The program responds

! with a run-time error. What is wrong? Use the do trace command to step

! through the program statement by statement. Write a corrected program that will

! handle this set of values.

! do trace, step (noerror$,x1,x2,a,b,c,extype,extext$)

 

! With the revised program the output is:

!Value of a? 3

!Value of b? 2

!Value of c? 2

!Unexpected error: SQR of negative number. Type= 3005

!Please try again.

!Value of a? 3

!Value of b? 2

!Value of c? -2

!The roots are .548584 and -1.21525

 

Sample output:

Value of a? 3

Value of b? 4

Value of c? 5

Unexpected error: SQR of negative number. Type= 3005

Please try again.

Value of a? 3

Value of b? 4

Value of c? -5

The roots are .7863 and -2.11963