montecarlo.cpp

来自「刚才传错了……这个才是采用蒙特卡罗法计算pi的近似值的源程序。方法是随机产生二维」· C++ 代码 · 共 30 行

CPP
30
字号
#include <stdio.h> 
#include <iostream> 
#include <time.h> 
using namespace std; 

void main(int argc, char* argv[]) 
{
 double t,x,y;
 int i,j=0,k;
 cout<<"Please input the number of times(integer):";
 cin>>t;
 while(t-int(t))
	{
	cout<<endl<<"Please input an integer:";
	cin>>t;
	} 
 
 srand( (unsigned)time( NULL ) );//srand()函数产生一个以当前时间开始的随机种子 
 for (k=9;k>=0;k--)
	{j=0;
	 for (i=1;i<=int(t);i++) 
		{
		 x=(1.0*rand())/RAND_MAX;//x、y的范围在0~1之间
		 y=(1.0*rand())/RAND_MAX;
		 if(x*x+y*y<1)j++;
		 }
	 cout<<4*j/t<<endl;
	}	 
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?