Notes on Integer Division and Truncation

The averaging calculation performed in response to the function call in line 12 of Fig. 4.8 produces an integer result. The sample execution indicates that the sum of the grade values is 846, which, when divided by 10, should yield 84.6—a number with a decimal point. However, the result of the calculation total / 10 (line 59 of Fig. 4.7) is the integer 84, because total and 10 are both integers. Dividing two integers results in integer division—any fractional part of the calculation is truncated. We’ll see how to obtain a result that includes a decimal point from the averaging calculation in the next section.


Image Common Programming Error 4.2

Assuming that integer division rounds (rather than truncates) can lead to incorrect results. For example, 7 ÷ 4, yields 1.75 in conventional arithmetic, but truncates the floating-point part (.75) in integer arithmetic. So the result is 1. Similarly, –7 ÷ 4, yields –1.


In Fig. 4.7, if line 59 used gradeCounter rather than 10, the output for this program would display an incorrect value, 76. This would occur because in the final iteration of the while statement, gradeCounter was incremented to the value 11 in line 55.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.87.83