/* TMA02 q4 */
/*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
double evaluatePI(long n); /*function evaluatePI declaration*/
int main(int argc, char **argv)
{
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 = %.20f\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;
}

double evaluatePI(long n) {  /*function body of evaluatePI,
                            it uses Euler's method to find out PI*/
long i = 0;                  /*index for for loop*/
double denomator = 0.0;      /*value of denomator*/
double sum = 0.0;            /*value of sum according to the number of terms*/
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*/
    denomator = (2*i-1)*(2*i-1);
    sum += (1/denomator);
    }
    return (sqrt(8 * sum));
}