954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Summing a series using recursion

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??

pearle
Newbie Poster
12 posts since Feb 2010
Reputation Points: 10
Solved Threads: 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.

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 

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

pearle
Newbie Poster
12 posts since Feb 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You