编写一个递归C++函数,计算并返回数组中整数的乘积
Write a recursive C++ function that computes and returns the product of the integers in an array
#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。
-
您必须使用
anArray[n-1]
而不是anArray[n]
,因为第三个元素的索引为3-1=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);
}
相关文章:
- 为什么 C++ 中的字符数组返回其项目而不是地址?
- C++ bool 数组返回 1 或 0 以外的值
- C++ ostream 从对象数组返回数据
- 类中的重载运算符 [],因此它可以从模板类中的数组返回对象
- 指向对象的指针数组返回jibberish
- 具有基本结构的结构数组返回错误的答案
- 数组返回乐趣 movie_check()
- C++从字符数组返回类型为T的指针
- C++-将数组返回到主函数,并将数组传递给另一个函数
- C++:如何通过异常处理从越界数组返回值
- 整数数组返回类型
- 从字符串流复制到 char * 数组返回为函数参数
- C++函数从对象数组返回对象的副本.这是默认行为吗?
- 8字节数组返回长(C#到C++)
- 向c#数组返回一个字符数组c++
- 从并行数组返回值,并在以后的函数中使用这些值
- 将c++中的浮点数数组返回给Python
- 如何在gsoap中使字符串数组返回值
- 将两个字符相乘并向数组返回int
- C++套接字 - 从结构数组返回单个地址信息