That's a good start. Now it needs de-bugging.
Depending on your compiler, you may get a warning message. Mine issues a warning about function a, "Function should return a value".
Anyway, let's take a closer look. If we use indentation and spacing to improve legibility, the problem may be come clearer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
double a (int b)
{
double c = 0;
double term;
int sign = 1;
for ( int i =1; i<=b; i++)
{
term = sign * 4* (1/(2*i-1));
c += term;
sign = -1 * sign;
return c;
}
}
|
Notice line 12,
return c;
is
inside the for loop. That means the first time around the loop, the value is returned, thus terminating the loop and the function as a whole. Move the return after line 13, outside the loop.
There's another problem, which you won't have noticed so far, as the above problem was hiding it.
If you temporarily insert this line, purely to see what is going on, inside the for loop (after line 10), it will show what is happening:
|
cout << " i: " << i << " term: " << term << endl;
|
... try it and see.
The problem here is all the values in the calculation of "term" are integers. That seems reasonable at first glance. But that means integer division will be used. The result of an integer divide is always a whole number, there cannot be any decimal places, the value is simply truncated.
A simple answer to that is to use values such as 4.0 and 2.0 instead of 4 and 2. That will force the compiler to use floating-point values rather than integers, and consequently it will use a floating-point divide operation.