我正在尝试在 C++ 上递归地查找数组元素的总和。
#include <bits/stdc++.h>
using namespace std;
int findSum(int arr[], int b, int e)
{
if(b == e)
return arr[b];
else
{
int mid = (b + e) / 2;
int x = findSum(arr, b, mid);
int y = findSum(arr, mid, e);
return x + y;
}
}
int main()
{
int arr[] = {1, 6, 3, 10, 11, 4, 5, 9, 15, 2};
cout << findSum(arr, 0, 9);
cout << endl; system("pause");
return 0;
}
运行后得到(Exception has occurred. Segmentation fault)
最佳答案
尝试在 C++ 中递归地做任何事情是危险的。您的程序将面临堆栈溢出的风险,因为它有多个重复的函数填充堆栈,每次调用自身时都会变大。
因此,您可以通过以下方式迭代执行此操作:
long int findsum(const int array[], int elementstart, int elementend) {
long int summedArray = 0;
for (int currentcell = elementstart; currentcell <= elementend; ++currentcell)
summedArray += array[currentcell];
return summedArray;
}
关于c++ - 尝试递归地获取数组元素的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58779210/