A program is being written to follow this instruction:
Report the average of 100 temperature readings, ignoring invalid readings.
The function read_sensor() gets one reading from a thermometer. It returns an integer from 0 through 1000 for a valid reading, or a negative integer for an invalid reading. Each call finishes within one millisecond. There is no guarantee about how often the thermometer will produce a valid reading.
Consider implementations A and B below. If either implementation finishes, the program divides sum by count using real division and displays the average. If count is zero, it displays "no usable data" instead. All sums fit in int.
/* A */
int sum = 0, count = 0;
for (int received = 0; received < 100; ++received) {
int x = read_sensor();
if (x >= 0) {
sum += x;
++count;
}
}/* B */
int sum = 0, count = 0;
while (count < 100) {
int x = read_sensor();
if (x >= 0) {
sum += x;
++count;
}
}On a test in which the first 100 readings are all valid, A and B display the same average.
The program is later given two explicit requirements:
- R1: Display the average of 100 valid readings.
- R2: Make no more than 1000 calls to
read_sensorbefore finishing.
The thermometer behaves as described above; these requirements do not change which readings it may produce.
