【发布时间】:2020-03-06 13:49:35
【问题描述】:
我对递归还是很陌生,我想从这个数组int arr[size] = {21, -6, 3, 5, 5, -3, 6, -21} 返回 3,因为它与递归实现具有相同的绝对值。
但是,我得到的值为 0。我无法确定是什么导致该程序没有带来预期的价值。
#include <iostream>
using namespace std;
int additive_inverse_opposite_pairs_count(int* arr, int n) {
int size = n;
if (n == 0) {
if (arr[n] == -1 * arr[size - 1 - n])
return 1;
else
return 0;
} else {
int count = additive_inverse_opposite_pairs_count(arr, n - 1) + count;
if (arr[n] == -1 * arr[size - 1 - n]) {
count += 1;
} else
count = 0;
return count;
}
}
int main() {
int size = 8;
int arr[size] = {21, -6, 3, 5, 5, -3, 6, -21};
int value = 0;
value = additive_inverse_opposite_pairs_count(arr, size);
cout << "value: " << value << endl;
return 0;
}
【问题讨论】:
-
欢迎来到 StackOverflow!该函数的预期返回值是多少?您是否尝试过测试您的功能是否适用于最简单的情况,例如大小列表
0、1、2? -
int count = ... + count;在初始化之前使用count并且具有未定义的行为。我怀疑您打算在函数调用之间“共享”count的值,但递归函数的工作方式与非递归函数完全一样;局部变量是特定函数调用的局部变量。