c++ - C++ 2 骰子滚动 1000 万次 BEGINNER
问题描述
我正在尝试创建一个程序,该程序将掷 2 个骰子 1000 万次,并输出每个数字掷了多少次。除此之外,我的任务是为输出创建直方图 (*=2000)。这是我到目前为止所拥有的。
/*
Creating a program that counts outcomes of two dice rolls, then show a
histogram of the outcomes.
Section 1 : Simulate ten million times rolls of two dice, while counting
outcomes. (Hint: Use an array of size 13.)
Section 2 : Show the outcome, the numbers of outcomes, and the histogram
(one * designates 20000). Your output must align properly.
*/
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int main()
{
int i, j, ary[13] = {};
cout << "Please enter the random number seed.";
cin >> j;
srand(j);
for (i = 0; i < 10000000; i++)
ary[die() + die()]++;
for (i = 2; i <= 12; i++)
{
cout << setw(3) << i << " : " << setw(6) << ary[i] << " : ";
for (j = 0; j < ary[i]; j += 2000)
cout << "*";
cout << endl;
}
return 0;
}
示例输出:https ://imgur.com/a/tETCj4O
我知道我需要用 rand() % 6 + 1; 在程序的开头。我觉得我接近完成但缺少关键点!我也意识到我没有在我的 ary[] 中定义 die()
解决方案
我建议从诸如 std::chrono::high_resolution_clock 之类的高精度计时器中创建随机种子。然后它们不依赖于用户并且实际上是随机的。总是在调用 std::rand 之前创建种子。
#include <chrono>
auto time = std::chrono::high_resolution_clock::now();
auto seed = std::chrono::duration_cast<std::chrono::milliseconds>(time);
std::srand(seed)
毫秒精度使种子通常足够独特,但如果种子需要接近每秒 1000 次,那么我建议使用纳秒或微秒精度来真正随机。
最好的方法是创建一个函数,使用高精度计时器和随机值创建随机种子,最后确保返回值在 0 到 5 之间(对于 6 面骰子)。
推荐阅读
- android - 禁止键盘弹出
- android - 如何使用 Glide 管理本地 Bitmap?
- java - getDrawable 兼容性问题
- php - 如何在自定义方程式中使用占位符创建 pdo mysql 准备语句?
- ruby-on-rails - Rails 在嵌套形式中使用子值
- javascript - 如何删除 javascript eslint
- jquery - 如何使用 ajax 代码修复 jquery localhost 说对象对象错误
- html - 向 Bootstrap 导航栏添加字幕
- python - Jupyter Notebook 不在虚拟环境中使用包
- android - Kotlin - 碎片中的房间