This laboratory exercise explores some practical consequences of the representation of data in program processing.
Recall from your prior work in C/C++ that constants variables INT_MIN and INT_MAX in C/C++ contain the smallest and largest int values available in C/C++.
Suppose i
and j
are two non-negative
integers, and a program is supposed to find their average (as an
integer). (In case the arithmetic average is a real number ending
in .5, then the average may be rounded either up or down. Thus, the
actual average 7.5 of 6 and 9 may be rounded to either 7 or 8.)
Five approaches are proposed to find this average:
avg1 = (i + j) / 2;
avg2 = i/2 + j/2;
avg3 = (i+1)/2 + j/2;
avg4 = i/2 + (j+1)/2;
avg5 = (i+1)/2 + (j+1)/2;
i
and j
? Explain.
i
and j
may be any
integers—positive, negative, or zero. In this general case,
which, if any, of these approachs will work reliably for all values
of i
and j
? Explain.
Consider the program integer-average.c.
Consider the code segment
double start = 7.0; double factor = 3.0; double quotient = start / factor; double result = quotient * factor; if (result == start) printf "start and result are the SAME\n"); else printf "start and result are DIFFERENT\n");
Include this code segment within a C program, using several values of start and with factor being 10.0, 5.0, 4.0, 3.0, and 2.0.
Consider program float-loop.c. As explained in the Reading on Consequences of the Data Representation of Numbers, repeated adding 0.1 to a number (starting at 0.0) never yields a result that is exactly 1.0.
Consider program arithmetic-series.c
created 31 March 2022 revised 31 March 2022 expanded 24 July 2022 |
|
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu. |