C ++ 2个骰子滚动1000万次BEGINNER

问题描述 投票:0回答:1

我正在尝试创建一个程序,将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()[]

c++ arrays loops dice
1个回答
0
投票

我建议从高精度计时器(例如std :: chrono :: high_resolution_clock)创建随机种子。然后它们不依赖于用户,实际上是随机的。

#include <chrono>

auto time = std::chrono::high_resolution_clock::now();
auto seed = std::chrono::duration_cast<std::chrono::milliseconds>(time);
std::srand(seed)

毫秒精度通常使种子具有足够的唯一性,但是如果要求种子每秒接近1000次,那么我建议使用纳秒或微秒精度是真正随机的。

© www.soinside.com 2019 - 2024. All rights reserved.