#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
unsigned int e;
int c;
void monte(int n ){
double x,y;
for (int i=0;i<n;i++){
x=(double)rand()/RAND_MAX;
y=(double)rand()/RAND_MAX;
if(x*x+y*y<1)c++;
}
}
int main()
{
int n;
double pi;
srand(time(0));
cin>>n;
monte(n);
pi=4.0*c/n;
printf("%11.61f",pi);
}
x^2+y^2<1 是因為假設
正方形的長度和圓半徑都為1
圓方程為 sqrt開根((x-中心x)^2+(y-中心y)^2))=r
也就是到圓中心的距離,設圓中心坐標(0,0),r為長度1
圓面積為 r^2*拍
1/4圓面為r^2/4 *拍 也就是 1/4 *拍
鏢落在圓的機率為 1/4*拍 除正方形面積= 1/4*拍
設機率為p =1/4*拍 換位會變 4*p=拍
也就是程式的 pi=4.0*c/n; c/n等於機率
留言列表