Hug*_*ggs 1 c++ arrays random c++14
当轧制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;
}
}
Run Code Online (Sandbox Code Playgroud)
以下是几个结果:
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
Run Code Online (Sandbox Code Playgroud)
为什么要计算这么多12?
尝试设置arraySize为13,而不是11.
有了11,你很幸运,不幸没有获得核心转储.
设置arraySize为11,frequency[11]并frequency[12]使用未定义的值进行初始化.
设置为13我得到
Face Frequency
2 999735
3 1999765
4 2997658
5 3998991
6 5003045
7 6002570
8 4999055
9 3999659
10 3000068
11 1999566
12 999888
Run Code Online (Sandbox Code Playgroud)
设置为11我得到
Face Frequency
2 998866
3 1999702
4 3001777
5 3999977
6 4999754
7 5999024
8 5000215
9 4000132
10 2999408
11 793621638
12 1000941
Run Code Online (Sandbox Code Playgroud)