首页 > 解决方案 > 为什么没有return语句的C++函数会返回一个值?

问题描述

我在 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 return value,但 cout 显示它但它不适用于我。)

标签: c++return

解决方案


为什么 C++ 函数...返回一个值?

您声明该函数返回一个值。因此该函数返回一个值。

...没有退货声明...

您未能编写退货声明。程序的行为是未定义的。

为什么返回该值?

因为程序的行为是未定义的。


推荐阅读