方法一:

 

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

double darts(int n) {
	srand(time(0));
	int k=0,i=0;
	double x,y;
	for(i=0; i<n; i++) {
		x=rand()/(RAND_MAX+1.0);
		y=rand()/(RAND_MAX+1.0);
//		x=rand()/32767.0;
//		y=rand()/32767.0;

		if(x*x+y*y<=1) {
			k++;
		}
	}
	return 4.0*k/n;
}

void main() {
	int n=0;
	printf("please input a number:");
	scanf("%d",&n);
	double pi=darts(n);
	printf("\n the pi is %f",pi);
}

 

 

方法二

 

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

double f(double x) {
	return sqrt(1-x*x);
}

double hitorMiss(double (*f)(double),int n) {
	srand(time(0));
	int k=0,i=0;
	double x,y;
	for(i=0; i<n; i++) {
		x=rand()/(RAND_MAX+1.0);
		y=rand()/(RAND_MAX+1.0);

		if(y<=((*f)(x))) {
			k++;
		}
	}
	return (4.0*k)/n;
}

int main() {

	int n=0;
	printf("please input a number:");
	scanf("%d",&n);

	double (*fx)(double);
	fx=&f;
	
	double pi=hitorMiss(f,n);
	printf("\n the pi is %f",pi);
	return 0;
}