Tính PI

Yêu cầu:

Tính PI với sai số 0.0001 theo công thức: PI/4 = 1 – 1/3 + 1/5 – 1/7 +…

Thuật toán:

– Dùng vòng lặp for().

– PI/4 = ∑(1 + ((-1)n/(2n+1)))

Code:

/************************************************************
* Author: VNCODING
* History 
* 2014/03/18 first create VNCODING
*************************************************************/
#include "stdio.h"
#include "conio.h"
#include "math.h"

#define E 0.0001

void main()
{
    float S = 0;
    float e = 1; // sai so e = 1/(2n + 1)
    int n = 0;
    while(e > E)
    {
        e = (float)1/(2*n + 1);
        if(n%2 == 0)
            S = S + e;
        else
            S = S - e;
        n++;
    }
    printf("\n PI = %f", 4*S);
    getch();
}

Kết quả:

PI = 3.141797

Be the first to comment

Leave a Reply