2.请补充例5. 7程序,分别统计当“fabs(t)>= le- 6”和“fabs(t)> = le- 8”时执行循环体的次数。
fabs(t)>= le- 6 ,示例代码
# include <stdio.h>
# include <math.h>
int main()
{
int sign = 1;
double pi = 0.0, term = 1.0;
int n = 0;
while (fabs(term) >= 1e-6)
{
n++;
term = 1.0 / (2 * n - 1)*sign;
pi += term;
sign = -sign;
}
pi *= 4;
printf("pi的近似值是%lf
", pi);
printf("循环体循环了%d次
", n);
return 0;
}
运行截图:
fabs(t)> = le- 8,示例代码
# include <stdio.h>
# include <math.h>
int main()
{
int sign = 1;
double pi = 0.0, term = 1.0;
int n = 0;
while (fabs(term) >= 1e-8)
{
n++;
term = 1.0 / (2 * n - 1)*sign;
pi += term;
sign = -sign;
}
pi *= 4;
printf("pi的近似值是%lf
", pi);
printf("循环体循环了%d次
", n);
return 0;
}
运行截图: