Two Answers to the Same Question

Medium

Build a small harness that makes rounding error visible and then shows the tolerant comparison surviving it. Each input line holds three numbers: a value, a count, and a target. The program adds the value to a running total that many times and then reports the total twice over, once as == judges it against the target and once as a tolerance of 1e-9 judges it. main is given to you and does the reading with the chapter 5 pair, fgets for a bounded read into a 128 byte line and sscanf(line, "%lf %d %lf", &value, &count, &target) for a checked parse, printing "bad line" and moving on whenever that count is not 3, and printing "no sums" when there was no input at all. It also does the printing, in the form "%.17g vs %.17g: == %s, tolerance %s\n", where %.17g is the seventeen significant digits that show what a double really holds and the two strings are "yes" or "no". What is missing is the two functions underneath. repeated_sum(double value, int count) returns 0.0 plus value added count times, written as a loop with total += value; inside it, and the loop is not an accident: one multiplication would round once where the loop rounds count times, and the accumulated drift is the whole thing the exercise exists to show. nearly_equal(double a, double b, double tolerance) returns whether the two are close enough, which is fabs(a - b) < tolerance and nothing else, with fabs from <math.h>, a header the platform links for you. The fabs is not decoration: a - b < tolerance without it is true for every case where a is smaller than b, however far apart they are, so the test would call 1.0 and 900.0 equal. Watch what the cases tell you. Ten additions of 0.1 land just below 1.0 and == says no; seven additions of 0.1 land exactly on the double that the literal 0.7 also becomes and == says yes; four additions of 0.25 are exact because a quarter is a power of two. You cannot predict which of those it will be by looking at the input, which is the argument for the tolerance. main returns 0 on every path including the empty one, since the checker treats a nonzero exit status as a failure however right the output looks.

Success Criteria

Your code must pass 7 test case(s) to complete this exercise. 3 hint(s) are available if you need help.

Sign in to track your progress

You can work on exercises as a guest, but sign in to track your progress and save your submissions.

This platform is built by its community

Every lesson, project, and tool on HelloC++ is funded by sponsors. Join them and help shape what we build next.

Become a Patron