/* TMA02 q4e */
/*Author: Chan Chi Ming s93504843, Date of authoring: 27/1/2001 */
/*This program is used to calcalate the value of PI.
 It can also used to test the performance of CPU.*/

#include <condefs.h>
#pragma hdrstop
#include <stdio.h>
#include <math.h>
#include <dos.h>

//---------------------------------------------------------------------------
#pragma argsused
long double evaluatePI(unsigned long n); /*function evaluatePI declaration*/
int main(int argc, char **argv)
{
unsigned long n;                    /*number of term*/
struct time t;
printf("Enter the number of terms (-1 to quit): ");
        /*ask user to input number of term or -1 to quit*/
scanf("%d", &n);
while(n != -1) {                  /*use a while loop to execute the function
                                    indefinitely until the input is -1*/
    gettime(&t);                  /*start time*/
    printf("The start time is: %2d:%02d:%02d.%02d\n",
          t.ti_hour, t.ti_min, t.ti_sec, t.ti_hund);
    printf("pi = %.20Lf\n", evaluatePI(n));  /*call the function and print out the result*/
    gettime(&t);                 /*end time*/
    printf("The finish time is: %2d:%02d:%02d.%02d\n",
          t.ti_hour, t.ti_min, t.ti_sec, t.ti_hund);
    printf("\n");
    printf("Enter the number of terms (-1 to quit): ");
    scanf("%d", &n);
    }
    return 0;
}

long double evaluatePI(unsigned long n) {  /*function body of evaluatePI,
                                  it uses Euler's method to find out PI*/
unsigned long i = 0;               /*index for for loop*/
long double denomator = 0.0L;      /*value of denomator*/
long double sum = 0.0L;            /*value of sum according to the number of terms*/
long double temp = 0.0L;
for(i=1; i<=n; i++)  {       /*using a for loop to calculate the value of pi
                                according to the no. of term, n, entered by user*/
    temp = static_cast <long double>((2*i-1)*(2*i-1));
    denomator = (1/temp);
    sum = sum + denomator;
    }
    return (sqrtl(8 * sum));
}