在 K&R 2-1 中解释这段代码 [英] Explain this code in K&R 2-1
本文介绍了在 K&R 2-1 中解释这段代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I'm trying to determine range of the various floating-point types. When I read this 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
", 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
", dblast);
return 0;
}
I don't understand why author added 1111e28
at fltest
variable ?
解决方案
The loop terminates when fltest
reaches +Inf
, as at that point fl = (fl + fltest) - fltest
becomes NaN
, which is unequal to 0.0
. last
contains a value which when added to 1111e28
produces +Inf
and so is close to the upper limit of float
.
1111e28
is chosen to reach +Inf
reasonably quickly; it also needs to be large enough that when added to large values the loop continues to progress i.e. it is at least as large as the gap between the largest and second-largest non-infinite float
values.
这篇关于在 K&R 2-1 中解释这段代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文