AP CSA Unit 1 Day 8: Casting Double To Int
Share
Casting double to int
Section 1.5 — Casting and Ranges
Key Concept
Compound assignment operators like +=, -=, *=, and /= perform an operation and assignment in one step. The expression x += 3 is equivalent to x = x + 3. However, there is a subtle difference: compound operators include an implicit cast. For example, byte b = 10; b += 5; compiles, while b = b + 5; does not because b + 5 produces an int. The increment (++) and decrement (--) operators are special cases that add or subtract 1.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) 9 10 10
Trace each cast carefully:
a: (int) 9.7 = 9. Casting truncates the decimal.
b: 9.7 + 0.5 = 10.2. Then (int) 10.2 = 10. The parentheses force addition before casting.
c: (int) 9.7 = 9. Then 9 + 1 = 10. The cast applies only to val, not to the addition.
Output: 9 10 10
Why Not the Others?
(B) This assumes casting rounds up. (int) 9.7 is 9, not 10. Casting always truncates toward zero.
(C) The third value is 10, not 11. (int) val + 1 casts val first (giving 9), then adds 1 (giving 10). If the cast applied to the whole expression, it would be (int)(9.7 + 1) = (int)(10.7) = 10, which is still 10.
(D) The second value is 10, not 9. The parentheses in (int)(val + 0.5) force the addition first: 9.7 + 0.5 = 10.2, then (int)(10.2) = 10.
Common Mistake
The key is understanding what the cast applies to. (int) val + 1 casts only val to 9, then adds 1. But (int)(val + 0.5) adds first, then casts the sum. Parentheses change everything.
AP Exam Tip
Draw a box around exactly what gets cast. (int) applies to the immediately following value or parenthesized expression. This distinction is a common AP exam trick.