BiB*_*iBo 0 c++ arrays random dice
我期待写称为小骰子游戏Farkle(你可能知道它从英国来delivarance)在C++中,但我还在学习,所以我有一些麻烦的.atm我正在尝试滚动6个骰子并将每个滚动的数字放在一个数组中以便以后可以使用它.一切似乎工作正常,但Visual Studio输出此错误代码:
运行时检查失败#2 - 变量'die'周围的堆栈已损坏.
这是我的代码:
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
void dice() {
int die[5];
int i = 1;
while (i <= 6) {
die[i] = rand() % 6 + 1;
cout << die[i];
i++;
}
}
int main()
{
srand(time(NULL));
dice();
system("STOP");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
对于这种程序来说,它实际上是正确的方法吗?
不,生成均匀分布的随机数的更好方法是
#include <random>
#include <algorithm>
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> d6(1, 6); // {1, 2, 3, 4, 5, 6} with equal probability
int die[5];
std::generate(die, die + 5, [&gen, &d6](){ return d6(gen); });
Run Code Online (Sandbox Code Playgroud)
如果您生成多组5d6,则可以重复使用它,gen而不是每次重新初始化它