ProgrammingVery hardProduct company OA
Assume IEEE-754 single-precision float with float arithmetic done in float. Which loops terminate?
Assume IEEE-754 single-precision float with float arithmetic done in float. Which loops terminate?
int c1 = 0, c2 = 0; for (float f = 0; f != 1.0f; f += 0.25f) c1++; /* (i) */ for (float f = 0; f != 1.0f; f += 0.1f) c2++; /* (ii) */
- A. Neither
- B. Only (i), after 4 passes
- C. Only (i), after 5 passes
- D. Both: (i) after 4 passes and (ii) after 10
Correct answer: B. Only (i), after 4 passes
0.25 is a power of two, exactly representable, so f hits 1.0 exactly after 4 additions. 0.1 has no exact binary form; ten rounded additions give 1.0000001, not 1.0, and the != test never becomes false. Use < or an integer counter for such loops.
More C Programming questions
- What is printed? c struct Shape { int w, h; int (area)(struct Shape ); }; int rect(struct Shape s) { return s->w s->h; } int tri(struct…
- What is printed? c int i = 0, s = 0; top: s += i; if (++i < 5) goto top; printf("%d %d", s, i);
- What is printed? c int calls = 0; int mx(int a, int lo, int hi) { calls++; if (lo == hi) return a[lo]; int m = (lo + hi) / 2; int l =…
- What is printed? c int a[] = {1, 2, 3}, p = a; int x = ++p++; int y = p++ 10; printf("%d %d %d %d", x, y, a[0], p);
- What is printed? c int x = 10; int p = &x, pp = &p; printf("%d", pp + p 2);
- What is printed? c const char s = " 42, 17"; printf("%zu %zu", strspn(s, " "), strcspn(s, ","));