ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int a = 7, b = 2;
double x = a / b;
double y = (double)a / b;
double z = (double)(a / b);
int w = (int)(-3.7) + (int)3.7;
int v = -7 / 2 * 2 + -7 % 2;
printf("%.1f %.1f %.1f %d %d", x, y, z, w, v);
  1. A. 3.5 3.5 3.0 0 -7
  2. B. 3.0 3.5 3.0 0 -7
  3. C. 3.0 3.5 3.0 -1 -8
  4. D. 3.0 3.5 3.5 0 -7

Correct answer: B. 3.0 3.5 3.0 0 -7

The type of a / b is fixed by its operands, not by where the result is stored: int / int = 3, then converted to 3.0. The cast binds tighter than /, so (double)a / b is a floating division (3.5), whereas (double)(a / b) casts too late. Conversion to int truncates toward zero: −3 + 3 = 0. Since C99, / also truncates toward zero and (a/b)*b + a%b == a, so −7/2 = −3, −7 % 2 = −1 and v = −6 − 1 = −7. The −1/−8 option uses floor semantics (Python's).

More C Programming questions

Exams that ask this topic