gpt4 book ai didi

c++ - 递归返回和基本流程

转载 作者:行者123 更新时间:2023-11-28 01:32:47 27 4
gpt4 key购买 nike

我无法理解有和没有返回的递归程序流程。如何返回或打印由函数计算的值组?例如,为了计算数组中的所有峰值元素,我使用了递归但我不知道如何给出这些值。基本上我不清楚如果我在递归函数之前写或不写 return 会发生什么。

int  peak(int arr[],int i,int size)
{
while(i<size)
{
if(arr[i]>arr[i+1]&&arr[i]>arr[i-1])
cout<<arr[i];
i++;
return peak(arr,i,size);
}
}

最佳答案

至少有两种方法可以解决您的问题。

第一个示例使用循环来计算峰值和:

int peak_sum(int arr[], int size)
{
int sum = 0;

// check first element
if (arr[0] > arr[1]) {
std::cout << arr[0] << std::endl;
sum += arr[0];
}

// for each middle value in array
for (int i = 1; i < size - 2; i++) {
// if current value is peak
if(arr[i] > arr[i + 1] && arr[i] > arr[i - 1]) {
std::cout << arr[i] << std::endl;
// then we add it to total sum of peaks
sum += arr[i];
}
}

// check last element
if (arr[size - 1] > arr[size - 2]) {
std::cout << arr[size - 1] << std::endl;
sum += arr[size - 1];
}

// after all we return this sum of peaks
return sum;
}

但是如果你想以递归的方式解决它,那么它可能看起来像这样:

int
peak_sum(int arr[], int size, int index, int sum)
{
// if index in bounds
if (index < size) {
// if we on the first element
if (index == 0) {
// if first element more then next: it is peak
if (arr[index] > arr[index + 1]) {
std::cout << arr[index] << std::endl;
sum += arr[index];
}

// if we on the last element
} else if (index == size - 1) {
// if first element more then previous: it is peak
if (arr[index] > arr[index - 1]) {
std::cout << arr[index] << std::endl;
sum += arr[index];
}

// else we in the middle
} else {
// if current element more then previous and next: it is peak
if (arr[index] > arr[index - 1] && arr[index] > arr[index + 1]) {
std::cout << arr[index] << std::endl;
sum += arr[index];
}
}

// anyway we check next value of array
// by incrimeting current index
return peak_sum(arr, size, index + 1, sum);
} else {
// otherwise we end iterating array
return sum;
}
}

并调用它:

//       array, size of it, initial index, initial sum
peak_sum(arr, array_size, 0, 0);

如果您对代码流感兴趣:

//example for array_size == 3

if (index in bounds) {
index++;
if (index in bounds) {
index++;
if (index in bounds) {
index++;
if (index in bounds) {}
else return sum;
}
}
}

关于c++ - 递归返回和基本流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50785853/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com