简体   繁体   中英

Approximation of Pi using Liebniz Formula in C++

First of all, I'm new to coding and C++. I did my researches for my problem on the internet but the solutions are not quite worked out for me.

I'm trying to get approximation of Pi with Liebniz formula which is: Pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9...

The code is compilable and runnable. The problem is I get 4 as answer for every number of iterations (n value). Here is the main part of the code.

int main() {

int i ;
double a=1  ;
double pi4 = 0 ; 
long n;
cout << "Number of iterations? ";
cin >> n;

for (i=1; i <= (n) ; i += 2) {

    pi4 = pi4 + a * (1 / i);
    a = -a;

}

cout.precision(20);
cout << "Pi = " << (pi4 * 4) << endl;
return 0;

Integer math. 1 / i will be 0 for all but the first iteration.

You can remove the reciprocal and just use a / i .

pi4 += a / i;

In c++ dividing by an int is this in other languages: floor(a / int). Convert "i" to a double, or "tell" the compiler, this is a floating-point division. (Because this is an integer dividing, or Euclidean division [https://en.wikipedia.org/wiki/Euclidean_division] [https://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division])

#include <iostream>

using namespace std;

int main() {

int i ;
double a=1  ;
double pi4 = 0 ; 
long n;
cout << "Number of iterations? ";
cin >> n;

for (i=1; i <= (n) ; i += 2) {

    pi4 = pi4 + a / i;
    // pi4 = pi4 + a * (1.0 / i);
    a = -a;

}

cout.precision(20);
cout << "Pi = " << (pi4 * 4) << endl;
return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM