Exercise 3: Translating "average <- total / count" Into a C-Family Language — Possible Solution ==================================================================== WHAT GOES WRONG WITH A DIRECT COPY ------------------------------ If total and count are both declared as integer types (for example, int in Java or C), the expression total / count uses that language's own integer division rule by default - the result is truncated toward zero and stored as another integer, discarding any fractional part entirely. For example, if total=10 and count=4, integer division gives 10/4 = 2 (the true mathematical result, 2.5, has its fractional part silently discarded) - a fundamentally different, less precise answer than Python 3's total/count, which this chapter confirmed always produces a float (10/4 = 2.5 in Python). WHAT THE PROGRAMMER NEEDS TO DO DIFFERENTLY ------------------------------ To get the same 2.5-style result Python 3's / operator would produce, at least one of the two operands needs to be explicitly converted to a floating-point type before the division happens - for example, casting total to a double/float type first (in C-family syntax, something like (double)total / count), or declaring one of the variables as a floating-point type from the start. Simply writing total / count with both operands left as integers will NOT automatically produce a fractional result in these languages, regardless of what the pseudocode's own / symbol might have implied. WHY COPYING THE / SYMBOL DIRECTLY ISN'T GUARANTEED TO BE CORRECT ------------------------------ This chapter established that pseudocode's own division symbol doesn't specify which division behavior (integer-truncating vs. floating-point) is intended - that decision has to be made explicitly by whoever translates the pseudocode into a specific language, because different mainstream languages default to genuinely different behavior for the identical-looking / operator on two integers. A translator who assumes the target language's / will behave the way Python 3's does (or the way the pseudocode author may have silently intended) risks introducing exactly the kind of averaging bug that under-reports fractional averages without any error or warning - the code compiles and runs without complaint, it just quietly produces a less precise answer. WHY THIS WORKS AS AN ANSWER ------------------------------ The answer identifies the specific mechanism (integer truncation by default for two integer operands in C-family languages), states the concrete fix (an explicit cast or floating-point declaration), and explains why the ambiguity is inherent to pseudocode's own division symbol rather than a mistake specific to this one example - directly extending this chapter's own general point about translation requiring deliberate, explicit choices.