【发布时间】:2017-12-16 02:48:25
【问题描述】:
当掷出 2 个六面骰子时,最常见的结果应该是 7,最不常见的结果应该是 2 和 12。
当我执行下面的代码时,我得到一个错误的数字 12 的高出现率。
#include <iostream>
#include <iomanip>
#include <random>
#include <ctime>
#include <array>
using namespace std;
int main() {
default_random_engine engine(static_cast<unsigned int>(time(0)));
uniform_int_distribution<unsigned int> randomInt(1, 6);
const size_t arraySize{11};
array<unsigned int, arraySize> frequency{};
for (unsigned int roll{1}; roll <= 36'000'000; ++roll){
++frequency[randomInt(engine) + randomInt(engine)];
}
cout << "Face" << setw(24) << "Frequency" << endl;
for (size_t sum{2}; sum <= 12; ++sum) {
cout << setw(4) << sum << setw(24) << frequency[sum] << endl;
}
}
以下是几个结果:
Face Frequency
2 1001328
3 1997709
4 2999938
5 4000842
6 4998363
7 5998813
8 5003114
9 4001434
10 3000068
11 1999298
12 5197605
Face Frequency
2 1001328
3 1997709
4 2999938
5 4000842
6 4998363
7 5998813
8 5003114
9 4001434
10 3000068
11 1999298
12 5197605
为什么要计算这么多 12?
【问题讨论】:
-
@EdHeal Yes, since C++14, "可选的单引号 (') 可以在数字之间插入作为分隔符。编译器会忽略它们。"
-
但标记为 C++11!
-
@IgorTandetnik 当我运行那个链接时,7s 实际上几乎每次都有最多的频率。哈哈
-
@EdHeal,好点子,看起来 Tas 解决了这个问题。