Novice C student here. I am trying to write a function called seriesSum that accepts one integer parameter and returns the sum n numbers following the pattern below.
// seriesSum(1) => 1 = "1.00"
// seriesSum(2) => 1 + 1/4 = "1.25"
// seriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57"
Simply summing n terms together with each terms' denominator increasing by three each term. The program should return the sum to two decimal places and return 0.00 if n = 0. n will only be given natural numbers (positive inters and 0).
However, any time I enter a value for n, I get 1.00 as output every time. I am not trying to re write the whole logic to my program; I am just hoping someone can point out the fallacy and why I get 1.00 every time. My code is below. Thanks in advance.
#include <iostream>
#include <string>
using namespace std;
double seriesSum(int n);
int main()
{
int n = 2;
seriesSum(n);
}
// write a function which returns the sum of following series up to nth
// parameter.
// need to round the answer to 2 decimal places and return as a string
// if the given value is 0, must return 0.00
// will only be given natural numbers as arguments
double seriesSum(int n)
{
double nDouble[n];
if (n == 0)
{
nDouble[0] = 0;
cout.precision(2);
cout << fixed << nDouble[0] << endl;
return nDouble[0];
}
else
{
nDouble[0] = 1;
int i;
for (i = 1; i < n; i++)
{
nDouble[i] = (1) / (1 + (3 * i));
}
double sum = 0;
int j;
for (j = 0; j < n; j++)
{
sum += nDouble[j];
}
cout.precision(2); // setting to 2 decimal places
cout << fixed << sum << endl; // not sure what fixed means but it works
return sum;
}
}