简体   繁体   English

C ++中的递归函数

[英]Recursive function in c++

All, 所有,

I'm writing a recursive function to do the following: 我正在编写一个递归函数来执行以下操作:

//addbig( ) -- This function is sent an array of integers and the length of the array.  
//It returns the sum of all integers in the array that are larger than 1000.

Somehow my function is not working. 不知何故我的功能无法正常工作。 It is giving me zero as the output. 它给我零作为输出。

long addbig (const int arrInt[],int l)
{
        if (l == 0)
            return 0;
    else if(arrInt[l]>1000)
        return  arrInt[l] + addbig (arrInt,l-1);
    else
        return  addbig (arrInt,l-1);
}

My integer array is: 我的整数数组是:

 int  arrInt[10]={1000,1,1000,2,1000,3,1000,4,1000,5};

Could anybody shed some light as to why this is not working, and help me a bit. 任何人都可以弄清楚为什么它不起作用,并为我提供一些帮助。 haha no pun intended 哈哈双关语意

First, none of the numbers in your test array are larger than 1000. So you would get 0. 首先,测试数组中的任何数字都不大于1000。因此,您将得到0。

Second, you are invoking UB: 其次,您正在调用UB:

long addbig (const int arrInt[],int l)
{
    if (l == 0)
        return 0;
    else if(arrInt[l] > 1000) // PROBLEM!
        return  arrInt[l] + addbig (arrInt,l-1);
    else
        return  addbig (arrInt,l-1);
}

If l is your array length, the first time you call this function will access 1 element beyond the array. 如果l是您的数组长度,则首次调用此函数将访问数组之外​​的1个元素。 What I think you want is: 我认为您想要的是:

long addbig (const int arrInt[],int l)
{
    if (l == 0)
        return 0;
    return addbig(arrInt, l - 1) + (arrInt[l - 1] > 1000 ? arrInt[l - 1] : 0);
}

Your base case is wrong. 您的基本情况是错误的。 I fixed it below. 我在下面固定了。 Note: none of the numbers in arrInt are greater than 1000, so you will always get zero as output. 注意: arrInt中的任何数字都不大于1000,因此输出总为零。

long addbig (const int arrInt[],int l)
{
        if (l <= 0)
            return 0;
    else if(arrInt[l-1]>1000)
        return  arrInt[l-1] + addbig (arrInt,l-1);
    else
        return  addbig (arrInt,l-1);
}
long addbig( const int a[], size_t n )
{
   const int LIMIT = 1000;
   return ( n == 0 ? 0 : a[0] > LIMIT + addbig( a + 1, n - 1 ) );
}

This can help you :D 这可以帮助您:D

#include <iostream>

using namespace std;

long addbig(const int arrInt[], int l)
{
    if (l == 0)
        return 0;
    else if (arrInt[l - 1] > 1000)
        return arrInt[l - 1] + addbig(arrInt, l - 1);
    else
        return addbig(arrInt, l - 1);
}

int main()
{
    int  arrInt[10] = {1001, 1, 2000, 2, 1000, 3, 1000, 4, 1000, 5};

    cout << addbig(arrInt, 10) << endl;

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM