/***************************************************
function
* Calculate pi by probability method and cutting method
Description
* Probability method requires a number of points not in the input circle
* The number of cuts required for the cutting method
***************************************************/
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
/* Probability method calculates pi */
int Probability_calculate_pi ()
{
int i,n,sum=0;
Double x, y;
printf ("Please input point count\n");//number of input points
scanf ("%d", &n);
Srand (Time (NULL));
for (i=0;i<n;i++)
{
x = (double) rand ()/rand_max; Generates a random number of 0~1 X
y = (double) rand ()/rand_max; Generates a random number of 0~1 y
if ((X*x + y*y) <=1)
{
sum++;
}
}
printf ("pi=%f\n", (double) 4*sum/n);
return 0;
}
/* Calculate pi */by cutting round
int Cyclotomic_calculate_pi ()
{
int i,n,s;
Double k,y2;
printf ("Please input incision count\n");//Input cut times
scanf ("%d", &n);
i = 0;
k = 3.0;
y2 = 1.0;
s = 6;
while (I<n)
{
printf ("The%dth incision,is%d, pi=%.24f\n", I,s,k*sqrt (y2));
s*=2;
y2 = 2-sqrt (4-y2);
i++;
k*=2.0;
}
return 0;
}
int main (int argc,char *argv[])
{
Probability_calculate_pi ();
Cyclotomic_calculate_pi ();
return 0;
}
The results of the operation are as follows:
C language learning in different ways to calculate pi