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

Recommended Answers

All 2 Replies

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.