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?

  1. A3.0 3.0
  2. B3.0 3.5
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. Which of the following is the output when the code above, which uses prefix and postfix ++, is executed?
  2. Which of the following is the output when the code above, with = written in the condition of an if statement, is executed?
  3. The code above was written to check whether bit 2 of the register value reg is 1. Which of the following is the result when it is executed?
  4. uint8_t is an 8-bit unsigned integer type. Which of the following is the output when the code above is executed?
  5. uint8_t is an 8-bit unsigned integer type. Which of the following is the output when the code above, which increments x ten times, is executed?