我的RNG值确定了意外值
My RNG value ascertains unexpected values
我知道随机并不是随机的,因此可以实现随时间的srand
,但是每次运行程序时,它并不是随机值,而是完全相同的值92和98,或2和2。我希望我的变量int randValPlayer = rand() % 20 + 1;
和int randValCPU = rand() % 20 + 1;
给出随机值。
我将srand(time(0));
放在我的主要功能中。我尝试更改预期值的随机算法。
class Game
{
private:
int playerHealth = 100;
int cpuHealth = 100;
int userChoice;
int randValPlayer = rand() % 20 + 1;
int randValCPU = rand() % 20 + 1;
public:
int attackPlayer()
{
playerHealth = playerHealth - randValPlayer;
return playerHealth;
}
int attackCPU()
{
cpuHealth = cpuHealth - randValCPU;
return cpuHealth;
}
void choice()
{
cout << "Input '1' to attack CPU" << endl;
cin >> userChoice;
if (userChoice == 1)
{
attackCPU();
cout << "CPU's health reduced to " << cpuHealth << endl;
attackPlayer();
cout << "Player health reduced to " << playerHealth << endl;
system("pause");
}
}
}gameobj;
class Foundation
{
private:
int userChoice;
public:
void startProgram()
{
cout << "Please input desired number: " << endl;
cout << "1. Calculator" << endl;
cout << "2. Equation calculator" << endl;
cout << "3. Game" << endl;
cin >> userChoice;
system("cls");
if (userChoice == 1) {
calcobj.calcOperation();
}
if (userChoice == 2) {
equationobj.equationChoice();
}
if (userChoice == 3) {
gameobj.choice();
}
}
}foundobj;
int main()
{
foundobj.startProgram();
srand(time(0));
return 0;
} ```
I expected the output to be random but the integer values are just the exact same, via 8 and 2.
您忘了考虑时间 - 您需要在使用发电机之前播种,但是您将其作为程序中的最后一件事。
即使您在main
中首先移动srand
,此程序也无法正常工作,因为在此之前创建了全局Game
实例。
由于(可变的(全局变量通常是一个坏主意,因此这是重写的好机会。
我建议这样的东西:
class Game
{
// ...
};
class Foundation
{
private:
Game gameobj;
// The other objects here...
public:
void startProgram()
{
int userChoice = 0;
cin >> userChoice;
// ...
if (userChoice == 3) {
gameobj.choice();
}
}
};
int main()
{
srand(time(0));
Foundation foundobj;
foundobj.startProgram();
return 0;
}
这里有很多错误:
1(您必须通过调用srand()
在 的任何调用rand()
来播种。当前,您在之后致电srand()
。因此,您将始终从rand()
获得相同的数字顺序。
2(time(0)
是一个相当糟糕的种子。它的分辨率仅为1秒,因此在同一秒内启动该程序的两个人都将获得相同的伪随机数。这也是一个高度猜测的种子。
3(您在诸如int randValPlayer = rand() % 20 + 1;
之类的语句中使用Modulo会引入偏差,如果rand()
的输出范围不能均匀地除以20。
4(rand()
(通常(的时间很短,输出范围有限。STD :: MT19937与std :: unibribil_int_distribution相结合,您可能会更好地为您服务。请参阅链接页面的示例。
相关文章:
- 在C++中对T*类型执行std::move的意外行为
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 处理除以零会导致<csignal>意外行为
- vscode下的Arduino代码出现意外编译错误
- 使用++运算符会导致意外的结果
- 套接字读取后,我在缓冲区中看到意外输入
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 使用vscode调试时,GDB意外退出
- 此测试()中发生了什么意外过程?为什么总是覆盖 ch[0 1 2..]?
- 尝试将字符串/字符转换为整数会产生意外结果
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- C++标头错误 C2238 意外标记";"
- C++中意外的多头值
- vector.size() 在比较中意外工作
- 使用 malloc() 时出现意外大小
- 多线程程序中出现意外的内存泄漏
- 为什么static_cast基础类型的枚举类int8_t获得意外值?
- 字符串比较中的意外输出
- 我的代码中的意外价值以及我如何修复它
- 我的RNG值确定了意外值