如题,积分函数选择e^x^2,积分区间为a,b
#include <iostream>
#include <ctime>
struct Point
{
float x, y;
};
int main()
{
srand((unsigned int)time(0));
int amount = 10000000;
Point* Sample = new Point[amount];
float a = 0, b = 2, fb = expf(b);
for (int i = 0; i < amount; i++) //随机打点
{
Sample[i].x = ((float)rand() / RAND_MAX) * (b - a);
Sample[i].y = ((float)rand() / RAND_MAX) * fb;
}
int k = 0;
for (int i = 0; i < amount; i++) //统计符合条件的样本
if (Sample[i].y <= expf(Sample[i].x))
k++;
// S = (符合条件的样本数量/总样本数量) * 打点矩形面积
std::cout << (float)k / amount * (b - a) * fb << '\n';
return 0;
}