话不多说,直接上代码
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
int main() {
const int num_points = 1000000; // 随机点的数量
int points_inside_circle = 0; // 圆内的点数
srand(time(0)); // 初始化随机数生成器
for (int i = 0; i < num_points; ++i) {
double x = static_cast<double>(rand()) / RAND_MAX * 2 - 1; // 随机生成x坐标,范围在[-1, 1]
double y = static_cast<double>(rand()) / RAND_MAX * 2 - 1; // 随机生成y坐标,范围在[-1, 1]
if (x * x + y * y <= 1) { // 如果点在单位圆内
++points_inside_circle;
}
}
double pi_estimate = 4.0 * points_inside_circle / num_points; // 计算圆周率的估计值
std::cout << "圆周率的估计值为: " << pi_estimate << std::endl;
return 0;
}