c++ - 为什么没有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++ 函数...返回一个值?
您声明该函数返回一个值。因此该函数返回一个值。
...没有退货声明...
您未能编写退货声明。程序的行为是未定义的。
为什么返回该值?
因为程序的行为是未定义的。
推荐阅读
- excel - Excel 多个 IF 语句、AND 语句和 MONTH 函数
- firebase - 使用 Firebase 实时数据库进行一对多关系查询
- css - 自定义字体(不使用@font-face)不会在 HTTPS 协议上加载
- python - 使用正则表达式将数据从字符串移动到熊猫数据框?
- apache-nifi - 单节点 Apache NiFi 集群
- reactjs - 在 react-admin 中实现 BackButton
- sql - PostgreSQL:根据一条记录中的值保留一组记录
- java - 使用@JoinTable 的休眠一对多映射问题
- javascript - Angular 6 订阅:无法读取未定义的属性“包含”
- python - pandas 在处理 nan 值的 groupby 对象上转换 nunique