c - Explain this code in K&R 2-1 -
i'm trying determine range of various floating-point types. when read code:
#include <stdio.h> main() { float fl, fltest, last; double dbl, dbltest, dblast; fl = 0.0; fltest = 0.0; while (fl == 0.0) { last = fltest; fltest = fltest + 1111e28; fl = (fl + fltest) - fltest; } printf("maximum range of float variable: %e\n", last); dbl = 0.0; dbltest = 0.0; while (dbl == 0.0) { dblast = dbltest; dbltest = dbltest + 1111e297; dbl = (dbl + dbltest) - dbltest; } printf("maximum range of double variable: %e\n", dblast); return 0; }
i don't understand why author added 1111e28
@ fltest
variable ?
the loop terminates when fltest
reaches +inf
, @ point fl = (fl + fltest) - fltest
becomes nan
, unequal 0.0
. last
contains value when added 1111e28
produces +inf
, close upper limit of float
.
1111e28
chosen reach +inf
reasonably quickly; needs large enough when added large values loop continues progress i.e. @ least large gap between largest , second-largest non-infinite float
values.
Comments
Post a Comment