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);- A. 3.5 3.5 3.0 0 -7
- B. 3.0 3.5 3.0 0 -7
- C. 3.0 3.5 3.0 -1 -8
- 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
- What is printed? c enum { RED = 2, GREEN, BLUE = GREEN + 4, N }; int a[] = { [RED] = 5, [BLUE] = 1, 9, [GREEN] = 6, 4 }; printf("%zu %d %d…
- Assume 8-bit char, 16-bit unsigned short and 32-bit int. What is printed? c int big = 300; unsigned char uc = big; unsigned short us = -1…
- What is printed? c int slot(int i) { static int box[3]; return &box[i % 3]; } int main(void) { slot(0) = 5; slot(4) = 7; int p = slot(3)…
- What is printed? c #define A 1 #define B #if defined(B) && A + C #define X 10 #else #define X 20 #endif #undef A #ifdef A #define Y 1…
- An array of int that may contain any values from INTMIN to INTMAX is sorted with qsort. With int x = (const int )a, y = (const int )b…
- What is printed? c int a[] = {4, 8, 15, 16, 23}; printf("%zu %d", sizeof(a) / sizeof(a[0]), a[sizeof(a) / sizeof(a[0]) - 1]);