Question

How to Define a function named calculatePI that takes a positive integer n as its argument...

How to Define a function named calculatePI that takes a positive integer n as its argument and calculates π using the formula: (Assume n is odd, which is the precondition of the function. And, this function should return double type value.) π = 4*(1 – 1/3 + 1/5 – 1/7 + 1/9 – 1/11 + ... 1/n)

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#include <iostream>

using namespace std;

double calculatePI(int n) {
    int i;
    double pi = 0, sign = 1;
    for (i = 0; i < n; ++i) {
        pi += sign * (1.0 / (2 * i + 1));
        sign *= -1;
    }
    return 4*pi;
}

int main() {
    cout << "Value of PI is " << calculatePI(10000) << endl;
    return 0;
}

Add a comment
Know the answer?
Add Answer to:
How to Define a function named calculatePI that takes a positive integer n as its argument...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT