【发布时间】:2020-06-15 16:12:22
【问题描述】:
我用C++实现了定点迭代,忘记了return语句:
double fixedpoint(double g(double), double p0, double tol, double max_iter)
{
double p, error, i = 1;
do
{
p = g(p0);
error = std::abs(p - p0);
i++;
p0 = p;
} while (i < max_iter && error > tol);
// No return statement
}
然后我调用了函数:
/* g(x) = (3x^2 + 3)^(1/4) */
double g(double x)
{
return pow(3 * x * x + 3, 0.25);
}
int main()
{
// Test
double p0 = 1;
double tol = 1e-2;
int max_iter = 20;
double p = fixedpoint(g, p0, tol, max_iter);
cout << "Solve x = (3x^2 + 3)^(1/4) correct to within 1e-2 using fixed-point iteration:" << endl;
cout << "Solution: x = " << setiosflags(ios::fixed) << setprecision(6) << p << endl;
}
我得到了以下结果:
Solve x = (3x^2 + 3)^(1/4) correct to within 1e-2 using fixed-point iteration:
Solution: x = 0.005809
实际上,0.005809 是最后一次迭代时error 变量(在fixedpoint 函数中)的值。为什么返回那个值?
我使用的是 GCC 版本 7.4.0。 (我也检查过Function not returning value, but cout displays it,但它不适用于我。)
【问题讨论】: