如何从递归函数中完全返回,该函数给出了每个函数结果的累积相加?
How to fully return from recursion function which gives cumulative addition of each function result?
我有函数用这个公式计算二项式系数p(n, x) = n!/(n-x)!.x!
由于实现是递归的,我想在结果系数超过 INT_MAX 时停止进一步的函数执行,它应该返回 -1。
但是,递归函数不是从这种情况返回,而是将此返回值视为内部递归函数返回的计算值。
这给出了错误的结果。
如何处理?
#include <iostream>
#include <cstdlib>
int INT_MAX = 100;
using namespace std;
int binomial_function(int n, int k){
int res = -1;
if (n<k || k<0 ){
return -1;
}
if(k == n || k == 0){
return 1;
}
res = binomial_function(n-1,k-1) + binomial_function(n-1,k);
if (res >= INT_MAX){ // checking overflow of res
return -1;
}
return res;
}
int main(int argc, char *argv[]){
int coefficient = 0;
coefficient = binomial_function(10,5); // actual binomial coeficient is 252 which overflows to INT_MAX
cout<<coefficient<<endl;
coefficient = binomial_function(10,6); // actual binomial coeficient is 210 which overflows to INT_MAX
cout<<coefficient<<endl;
coefficient = binomial_function(10,8); // actual binomial coeficient is 1 which does overflows to INT_MAX
cout<<coefficient<<endl;
return 0;
}
实际输出为:
-2
83
45
预期产出:
-1 >> this should be result because coefficient exceeds INT_MAX
-1 >> this should be result because coefficient exceeds INT_MAX
45 >> this should be result because coefficient does not exceeds INT_MAX
在执行添加之前,您应该检查返回值是否不是错误。
int res1, res2;
res1 = binomial_function(n-1,k-1);
res2 = binomial_function(n-1,k);
if (res1 < 0 || res2 < 0){ // checking errors of return values
return -1;
}
res = res1 + res2;
if (res >= INT_MAX){ // checking overflow of res
return -1;
}
相关文章:
- 如何从递归函数中完全返回,该函数给出了每个函数结果的累积相加?
- 分段错误分配函数结果
- 使用函数结果作为参数的 C++
- 从可调用可变参数元组中的函数结果创建元组
- 将多个向量(函数结果)组合到一个使用模板中
- 是否可以使用自动占位符来推断非类型模板参数中的函数结果
- 大小由虚函数结果决定的数组
- C/C++编译器是否会通过重用最近计算的函数结果来优化代码?
- 从函数结果中分配 std::shared_ptr 的一行是什么?
- 将函数结果分配给变量的问题
- std::具有自定义比较函数结果的排序函数错误:必须调用对非静态成员函数的引用
- C++SFINAE运算符/函数结果类型检查
- 将函数结果作为"output parameter"返回是什么意思?
- 这将是在将函数分配给变量或一次又一次地调用函数之间使用函数结果的最佳方式
- C++中的绑定函数结果
- 有没有比生成/累积更快的方法来计算函数结果的平均值
- 为什么当递归函数结果相乘时,g++ 仍然优化尾递归
- C++成员函数结果缓存实现
- 用于输出列中对数函数结果的合适循环(c++)
- 将记录作为函数结果从Delphi DLL传递到c++