kor*_*ina 0 c++ random for-loop
这个程序应该是一个非常原始的老虎机,有三个不同的"轮子"可以旋转.每个轮子包含一定数量的字符.函数生成一个随机数,以指定每个轮中的数组位置,然后生成对应于该位置的符号.
我遇到的问题是随机生成的数字不会在我的for循环的每次迭代中发生变化.所以我基本上每次循环都会得到"X-X"或"X @ - ".我搜索了之前提出的问题并找到了几个相关问题,但似乎没有一个能解决我的问题.
道歉的代码:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
const int WHEEL_POSITIONS = 30;
const char wheelSymbols[WHEEL_POSITIONS + 1] = "-X-X-X-X-X=X=X=X*X*X*X*X@X@X7X";
struct slotMachine
{
char symbols[WHEEL_POSITIONS + 1];
int spinPos;
char spinSymbol;
} wheels[3];
void startWheels(slotMachine []);
void spinWheels(slotMachine []);
void displayResults(slotMachine []);
bool getWinner(slotMachine []);
int main(void)
{
int spinNum;
cout << "How many times do you want to spin the wheel? ";
cin >> spinNum;
// Calls startWheels function
startWheels(wheels);
for (int i = 0; i < spinNum; i++)
{
// Calls spinWheels function
spinWheels(wheels);
// Calls displayResults function
displayResults(wheels);
// Calls function getWinner; if getWinner is true, outputs winning message
if (getWinner(wheels) == true)
{
cout << "Winner! Matched 3 of " << wheels[0].spinSymbol << "." << endl;
}
}
return 0;
}
// Function to initialize each wheel to the characters stored in wheelSymbols[]
void startWheels(slotMachine fwheels[3])
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < (WHEEL_POSITIONS + 1); j++)
{
fwheels[i].symbols[j] = wheelSymbols[j];
}
}
}
// Function to generate a random position in each wheel
void spinWheels(slotMachine fwheels[3])
{
time_t seed;
time(&seed);
srand(seed);
for (int i = 0; i < 3; i++)
{
fwheels[i].spinPos = (rand() % WHEEL_POSITIONS);
}
}
void displayResults(slotMachine fwheels[3])
{
for (int i = 0; i < 3; i++)
{
fwheels[i].spinSymbol = fwheels[i].symbols[(fwheels[i].spinPos)];
cout << fwheels[i].spinSymbol;
}
cout << endl;
}
bool getWinner(slotMachine fwheels[3])
{
if ((fwheels[0].spinSymbol == fwheels[1].spinSymbol) && (fwheels[0].spinSymbol == fwheels[2].spinSymbol) && (fwheels[1].spinSymbol == fwheels[2].spinSymbol))
{
return true;
}
else
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我确信这很简单,我很遗憾,但我找不到它!
每次调用该函数时,您都会重新播种随机数生成器spinwheels.
将这三行移动到main函数的顶部.
time_t seed;
time(&seed);
srand(seed);
Run Code Online (Sandbox Code Playgroud)
当我们使用生成随机数时rand(),我们实际上使用伪随机数生成器(PRNG),它根据称为a的特定输入生成固定的随机值序列seed.当我们设置种子时,我们有效地重置序列以再次从同一种子开始.
您可能认为使用time每次会导致不同的种子,每次仍然会给您不同的结果,但在快速的计算机程序中,所以很少有时间通过,在每次调用期间种子实际上没有变化.
这就是为什么,正如另一个答案所提到的,你应该只srand()在你的程序中调用一次.