编写递归C ++函数,计算并返回数组中整数的乘积

时间:2014-04-22 20:30:32

标签: c++ recursion

#include<iostream>
using namespace std;

int theProduct(int anArray[], int n);

int main(int argc, const char * argv[])

{

    int myArray[3] = {1, 2, 3};

    cout << "The product of the array elements of myArray is "<<theProduct(myArray,3)<<endl;

    return 0;
}

int theProduct(int anArray[], int n)
{

    if (n <= 0)
        return 0;

    else if (n == 1)  //base case
        return anArray[0] * anArray[1];
    else
        return anArray[n] * theProduct(anArray, n - 1);

}

我希望我的输出为6,而我的输出是&#34; myArray的数组元素的乘积是1048565344&#34; 请告诉我我做错了什么。

4 个答案:

答案 0 :(得分:3)

如果大小为1,则只有一个元素,因此在

else if (n == 1)  //base case
    return anArray[0] * anArray[1];

通过访问anArray[1],您实际上已经超出界限。

在:

else
    return anArray[n] * theProduct(anArray, n - 1);

如果尺寸为n,则您无法访问anArray[n],因为元素会从0计算到n-1。例如,在数组中,大小为3,但元素具有索引:0, 1, 2

你的意思是:

int theProduct(int anArray[], int n) {
    if (n <= 0)
        return 0;
    else if (n == 1)
        return anArray[0];
    else
        return anArray[n-1] * theProduct(anArray, n - 1);
}

Live demo

正确输出6

答案 1 :(得分:0)

  1. 您必须使用anArray[n-1]代替anArray[n],因为第3个元素的索引为3-1 = 2.

  2. 不要返回anArray[0] * anArray[1]anArray[0],因为您已经与anArray[1]

  3. 相乘

    您的代码包含更改(以及更小的代码):

    #include <iostream>
    
    using namespace std;
    
    int theProduct(int anArray[], int size) {
        if (size <= 0)
            return 0;
        else if (size == 1)  // base case
            return anArray[0];
        else
            return anArray[size - 1] * theProduct(anArray, size - 1);
    }
    
    int main(int argc, const char * argv[])
    {
        int myArray[3] = {1, 2, 3};
    
        cout << "The product of the array elements of myArray is "
             << theProduct(myArray,3) << endl;
    
        return 0;
    }
    

答案 2 :(得分:0)

我说这应该运作良好。您应该使用数组的最大索引调用该函数:

cout&lt;&lt; &#34; myArray的数组元素的产品是&#34; &LT;&LT; theProduct(myArray,2)&lt;&lt; ENDL;

答案 3 :(得分:0)

这是一个替代版本,它使用辅助函数和递归函数,递归地将数组拆分为两部分。它将使用log2(n)级别的递归而不是n级递归,从而减少堆栈开销。

#include<iostream>
using namespace std;

int Product(int A[], size_t n);
int ProductR(int A[], size_t low, size_t end);

int main(int Argc, const char * argv[])
{
    int A[] = {1, 2, 3, 4, 5, 6, 7};
    cout << "The product of the array elements of myArray is " <<
            Product(A, sizeof(A)/sizeof(A[0])) << endl;
    return 0;
}

int Product(int A[], size_t n)
{
    return ProductR(A, 0, n);
}

int ProductR(int A[], size_t low, size_t end)
{
    if((end - low) == 0)
        return 1;
    if((end - low) == 1)
        return A[low];
    size_t mid = (low + end)/2;
    return ProductR(A, low, mid) * ProductR(A, mid, end);
}