Practice Program 5.1. Rounding numbers.

The following program automates the number input by placing the values in a data statement and comparing different functions that could be used to round them.

PP5.1

! Ask a user for a positive or negative number and display

! it rounded to the nearest integer. If 11.5 is entered, 12

! should be displayed.

 

! Test your program using the numbers 11.5, -6.7, 3.95, 9.11,-3.95.

! Compare the functions "round(number)", "truncate(number,0)", "int(number)"

! by restoring the data and repeating the calculation for each function.

! Note that only "round(number)" produces 12 from 11.5 (the others get 11).

 

! Pseudo code.

! Input the numbers to be tested with a data statement.

! Input from the keyboard commented out.

! The function that rounds to the nearest integer is int(x)

! Test with do trace, slow (count)

 

LET count=0

PRINT "count","number","round(number)"

DO until end data

LET count=count+1

READ number

PRINT count,number,round(number)

LOOP

RESTORE ! reads in the data again

LET count=0

PRINT "count","number","truncate(number,0)"

DO until end data

LET count=count+1

READ number

PRINT count,number,truncate(number,0)

LOOP

RESTORE

LET count=0

PRINT "count","number","int(number)"

DO until end data

LET count=count+1

READ number

PRINT count,number,int(number)

LOOP

DATA 11.5, -6.7, 3.95, 9.11,-3.95

END ! only round(number) satisfies the problem statement.


The output for this program is:

count number round(number)

1 11.5 12 ( this is the desired result)

2 -6.7 -7

3 3.95 4

4 9.11 9

5 -3.95 -4

count number truncate(number,0)

1 11.5 11

2 -6.7 -6

3 3.95 3

4 9.11 9

5 -3.95 -3

count number int(number)

1 11.5 11

2 -6.7 -7

3 3.95 3

4 9.11 9

5 -3.95 -4

Note that all of these functions give slightly different results.