每当我运行程序时,我收到的pi的返回值都会直接增加我输入的点数。我一直在遵循蒙特卡洛pi估计方法,该方法涉及随机生成的0到1之间的数字。
例如,当我运行程序并输入29点时,我的pi估计值为29。
https://www.geeksforgeeks.org/estimating-value-pi-using-monte-carlo/
// piCalculator.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
using namespace std;
double piEstimator(int numPts);
int main()
{
cout << rand();
int numPts;
cout << "How many points would you like to use to estimate pi?" << endl;
cin >> numPts;
float piEstimation = piEstimator(numPts);
cout << "Your estimation for pi is " << numPts << endl;
return 0;
}
double piEstimator(int numPts) {
double x, y, dist, piEstimation;
double dotsCirc = 0;
double dotsTotal = 0;
for (int i = 0; i < numPts; i++) {
x = static_cast <double> (rand()) / static_cast <double> (RAND_MAX);
y = static_cast <double> (rand()) / static_cast <double> (RAND_MAX);
dist =(x * x) + (y * y);
if (dist <= 1) {
dotsCirc++;
}
dotsTotal++;
}
piEstimation = (4*dotsCirc/dotsTotal);
return piEstimation;
}
每当我运行程序时,我收到的pi的返回值都会直接增加我输入的点数。我一直在遵循蒙特卡洛pi估计方法,涉及随机...
您正在打印点数而不是估计的pi。