话不多说,直接上代码
#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;
}

该篇文章展示了如何使用C++编程语言通过生成随机点并计算落入单位圆内的点数来估算圆周率,通过统计比例得到π的近似值。
1万+

被折叠的 条评论
为什么被折叠?



