Approximating the pi

 avatar
unknown
c_cpp
a year ago
769 B
8
Indexable
#define _CRT_SECURE_NO_WARNINGS

#include <math.h>
#include <stdio.h>

double PIfunc(int nod) {
    double eps = 1 / (pow(10, (double)nod + 1));

    double sum = 0;
    double term = 0;
    int sgn = 1;
    long long int iter = 0;
    int i = 0;

    while (1) {
        term = 4 * ((double)sgn / ((double)i * 2 + 1));
        iter++;
        sgn = sgn * (-1);
        sum = sum + term;
        i++;

        if (sgn * term * (-1) < eps) {
            break;
        }
    }
    printf("\n\nPrecision is: %d", nod);
    printf("\nThe number of iterations is: %lld", iter);
    return sum;
}

int main(void) {

    for (int nodp = 1; nodp <= 9; nodp++) {
        double pi = PIfunc(nodp);
        printf("\nThe value of pi: %.*lf", nodp, pi);
    }
    
    return 0;
}
Editor is loading...
Leave a Comment