0

Hi, everybody. I've started learning about recursion, but I'm having a hard time completely understanding it. I've tried to write a simple recursive function that returns the sum of the series m(i) = (1/3) + (2/5) + (3/7) + (4/9) + ... (i / (2i + 1)), but I keep getting the wrong output. This is the code:

#include <iostream>
using namespace std;

double seriesFunc(int n)
{
       if (n == 0) return 0;
       else if (n == 1) return 1/3.0;
       else return (n / (2 * n + 1)) + seriesFunc(n-1);
}
       
int main()
{
    cout << seriesFunc(6) << endl;
    cout << seriesFunc(2) << endl;
    return 0;
}

This is my ouput:

0.33333333
0.33333333

Can anyone help??

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by pearle
0
else return (n / (2 * n + 1)) + seriesFunc(n-1);

The first portion is being computed with integers, so you need to cast either the numerator or the denominator (or both) to a double.

0

Wow, what a silly mistake I made. Thanks for pointing it out! The program now works. :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.