编写C ++递归函数以计算并显示数组中前n个double的乘积

时间:2018-09-05 15:50:43

标签: c++ arrays recursion

#include "stdafx.h"
#include <iostream>

using namespace std;

void countDown(int n);
double computeProduct(const double anArray[], int n);

int main()
{
    //Stand alone test of computeProduct function.

    double Array[10] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};
    computeProduct(Array, 4);
    cout << endl;
    system("pause");



    return 0;
}
double computeProduct(const double anArray[], int n)
{

    if (n == 1) {

        return anArray[0];

    }
    else {

        cout << anArray[n-1] * computeProduct(anArray, n-1);    

    }
}

这应该可以工作,但是由于某些原因,当我运行程序时,控制台会返回: 2-nan(ind)-nan(ind) 按任意键继续...

我以前从未见过-nan(ind),也不知道该做什么或做了什么。
任何和所有帮助将不胜感激! :)

2 个答案:

答案 0 :(得分:2)

您的函数computeProduct()仅在n = 1时有效。否则,它将返回未定义的值。 您的编译器可能会警告您,例如“并非所有控制路径都返回值”。

解决此问题的一种方法是添加一个附加变量:

 double computeProduct(const double anArray[], int n)
 {                
     double product = 0.0; 

     if (n == 1) {                        
         product = anArray[0];                        
     }
     else {
         product = anArray[n-1] * computeProduct(anArray, n-1);                        
     }                
     //add your debug information here ...
     cout << "return value for index n = " << n << " is " << product;

     return product ;
}

答案 1 :(得分:0)

如果n!= 1,则您编写的函数没有明确的返回值。这是未定义的行为,在您的情况下,这意味着有效返回的值是垃圾。

对程序进行简单的修改即可解决问题。请注意,您需要考虑小于1的大小,否则将出现段错误。

double computeProduct(const double anArray[], int n)
{
    if (n <= 0) {
        return 0.0;
    } else if (n == 1) {
        return anArray[0];
    }
    else {
        return anArray[n-1] * computeProduct(anArray, n-1);    
    }
}
...
cout << computeProduct(Array, 4)<< endl;

最好的递归函数分为两个,一个使用累加器,另一个提供所需的接口:

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

double computeProduct(const double anArray[], int arraySize, int n) 
{
    if(n > arraySize || n <= 0) {
      return 0.0
    }
    return computeProductAcc(anArray, n, 1.0)
}