Logo C++ Online Judge

C++

TA:
统计

A program stores its numbers as 32-bit float values. These values have limited precision: for example, storing 100000001 gives 100000000. An addition also rounds its result to the nearest value that a float can store.

You can explore this behavior with Float Toy.

Three numbers. Let a = 1, b = 100000000, and c = -100000000. All three are stored exactly. Evaluating the following expressions gives the shown results:

(a + b) + c   /* observed result: 0 */
a + (b + c)   /* observed result: 1 */

A longer sum. The program next adds one number equal to 100000000 and 128 numbers equal to 1. If it starts with 100000000 and adds each 1 separately, the stored total remains 100000000. However, both 128 and 100000128 can be represented exactly as floats. You may change the order or grouping of the additions, but you must still use float arithmetic.

A different addition function. A function named precise_sum promises the same result as adding its input values exactly and then rounding the total to a float.

The program reads the original decimal measurements, stores each one as a float, and then passes those stored values to precise_sum.

提交

Written answers receive AI rubric assessment.

Up to 3 submission attempts per student. Sign in to see your remaining attempts.

Each submission includes all questions. Review your answers before submitting.

Short explanations are welcome. You may leave answers blank; unanswered questions receive zero credit.

1. Why do (a + b) + c and a + (b + c) give different results for the three numbers shown? Which one gives their exact mathematical sum? (30 points)
2. When adding 100000000 and the 128 ones, how would you arrange the additions so that the ones contribute to the result? Explain why your arrangement works here; no code is needed. (35 points)
3. If the program needs to keep 100000001 and 100000000 distinguishable, is changing the addition function to precise_sum sufficient? Explain where in the program that distinction would need to be preserved. (35 points)
Drafts are saved in this browser every 30 seconds.