1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| #include <iostream> #include <vector> #include <random> #include <algorithm> #include <cmath>
using namespace std;
double getArcLength(double a, double b) { double diff = abs(a - b); return min(diff, 1.0 - diff); }
bool isObtuseTriangle(double x1, double x2, double x3) { vector<double> points; points.push_back(x1); points.push_back(x2); points.push_back(x3); sort(points.begin(), points.end()); double arc1 = getArcLength(points[0], points[1]); double arc2 = getArcLength(points[1], points[2]); double arc3 = getArcLength(points[2], points[0]); double oppArc1 = arc2 + arc3; double oppArc2 = arc1 + arc3; double oppArc3 = arc1 + arc2; return (oppArc1 < 0.5 || oppArc2 < 0.5 || oppArc3 < 0.5); }
int main() { random_device rd; mt19937 gen(rd()); uniform_real_distribution<> dis(0.0, 1.0); int trials = 1000000; int obtuseCount = 0; for (int i = 0; i < trials; i++) { double x1 = dis(gen); double x2 = dis(gen); double x3 = dis(gen); if (isObtuseTriangle(x1, x2, x3)) { obtuseCount++; } } double probability = static_cast<double>(obtuseCount) / trials; cout << "模拟次数: " << trials << endl; cout << "形成钝角三角形的次数: " << obtuseCount << endl; cout << "概率: " << probability << endl; cout << "理论值: 0.75" << endl; return 0; }
|