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

Write a recursive C++ function that computes and returns the product of the integers in an array

本文关键字:数组 返回 计算 整数 函数 C++ 递归 一个      更新时间:2023-10-16
#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,结果是"myArray的数组元素的乘积是1048565344"请告诉我我做错了什么。

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

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

访问CCD_ 2实际上是越界了。

In:

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);
}

现场演示

其正确地输出CCD_ 9。

  1. 您必须使用anArray[n-1]而不是anArray[n],因为第三个元素的索引为3-1=2。

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

这是您的代码更改(以及一些较小的更改(:

#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;
}

我认为这应该能很好地工作。您应该使用数组的最大索引调用函数:

cout<lt;"myArray的数组元素的乘积是"<lt;产品(myArray,2(<lt;endl;

这里有一个替代版本,它使用了一个辅助函数和一个递归函数,递归函数将数组分为两部分。它将使用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);
}