Calclating pi from sum of infinite series

Hi there,

Here is my code for the calculation of pi from the sum of an infinite series:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int main()
{
    // Declare and initalise variables
    int decPlaces;
    double fraction=0, pi=0;

    cout << "Program to calculate pi using the sum of an infinite series" << endl;
    cout << "Please input the number of decimal places to display: " << endl;
    cin >> decPlaces;
    cout << endl;

    // calculate the value for pi using a 100 step loop
    for ( int n = 1; n <= 100; n++ )
    {
        fraction = (4*pow(-1, n+1))/(2*n - 1);
        pi = pi + fraction;
    }

    // Output the value of pi correct to user input number of decimal places
    cout << "The value of pi is: " << setprecision(decPlaces) << fixed << pi << endl;

    return 0;
}


I am having trouble with the power in the for loop. It keeps giving me the error C2668: 'pow' : ambiguous call to overload function. Can you help?

Also, is there anything which is bad programming practice in the code above... anything that should be modified?

Thanks :)
pow hasn't overloads for integral types so it can generate errors, convert an argument to a floating point type
eg: pow(-1.0, n+1)
-1.0 has as type double and with that you shouldn't get error messages
Topic archived. No new replies allowed.