C Programming Basics
int a = 7, b = 2;
double x = a / b;
double y = (double)a / b;
printf("%.1f %.1f\n", x, y);Which of the following is the output when the code above, which includes a division of integers, is executed?
- A3.0 3.0
- B3.0 3.5
- C3.5 3.5
Show answer and explanation
Answer: B. 3.0 3.5
a / b divides an int by an int, so it is integer division and gives 3, with the fractional part discarded. Putting that 3 into the double x only makes it 3.0; the discarded 0.5 does not come back. For y, a is converted to double first (a cast), so b is also converted to double, the division is done in floating point and the result is 3.5. How the calculation is done is decided by the types of the operands, not by the type of the variable being assigned.
- A. For y, a is converted to double before dividing, so the floating-point division gives 3.5.
- B. Correct. x is 3.0, converted from the integer quotient 3, and y is 3.5 from floating-point division.
- C. x is 3 from int-by-int division before being converted to double, so it is not 3.5.