Recursive Sum of Series
I'm trying to write a recursive function that calculates the sum of the first n terms in the series: 1 + 1/2 - 1/3 + 1/4 - 1/5... n.
This is what I've written, but I'm currently only getting 0 printed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
using namespace std;
double sum(int n) {
int value = 0;
if(n==1) {
return n;
}
else if (n%2 == 0) {
value = 1.0/n + sum(n-1);
return value;
}
else {
value = 1.0/n - sum(n-1);
return value;
}
return value;
}
int main() {
cout << sum(4) << endl;
}
|
Any trips would be appreciated!
Any trips would be appreciated! |
If you get any extra trips send me one!
I don't know if this is the correct answer but I got
by changing
int value
to
double value
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
using namespace std;
double sum(int n) {
double value = 0;
if(n==1) {
return n;
}
else if (n%2 == 0) {
value = 1.0/n + sum(n-1);
return value;
}
else {
value = 1.0/n - sum(n-1);
return value;
}
return value;
}
int main() {
cout << sum(4) << endl;
}
|
haha my bad on that one.
It wasn't, but I fixed it by changing the 1.0/n to the end of the line. Thanks!
Topic archived. No new replies allowed.