//蒙特卡洛法求圓周率
#include
#include
#include
#include
using namespace std;
double FindPi(const long n)
{
srand(time(NULL));
long sum = 0;
double x = 0.0, y = 0.0;
for (long i = 0; i < n; i++)
{
x = (double)(rand())/(double)RAND_MAX;
y = (double)(rand())/(double)RAND_MAX;
if (x*x + y*y <= 1)
{
sum++;
}
if (i % 10000 == 0)
{
system("clear");
cout<<"運行了"<<i<<"次運算,完成了總運算的"<<(double)i/(double)n*100.0<<"%"<<endl;
}
}
return 4.0*((double)sum/(double)n);
}
int main()
{
long n = 0;
cout<<"輸入模擬次數:";
cin>>n;
if (n <= 0)
{
cout<<"輸入錯誤"<<endl;
exit(1);
}
double pi = FindPi(n);
cout.precision(50);
cout<<"模擬"<<n<<"次,pi = "<<pi<<endl;
return 0;
}
這個代碼為什麼算出來的總是在3左右,而不是3.14?
選取的樣本是不是太小了?改大點看看。