我用C++做了一个有趣的小游戏,我做了一个介于0和100之间的随机数,这是你需要解决的威胁的数量,这是可行的,但我做了一个HomeScreen()函数,如果用户想要回去查看威胁或输入命令,就会调用它,问题是当我调用我的int表示威胁时,它会创建一个新的随机数来扰乱整个游戏,因为它会擦除或阻碍用户的进程。我需要知道如何获取游戏启动时生成的威胁数,并将其显示在HomeScreen()函数中。
main.cpp (the first place where the int and random value is assigned)int threats; srand(time(NULL)); threats = rand() % 100 + 1;
HomeScreen() Function
int threats;
srand(time(NULL));
threats = rand() % 100 + 1;
system("CLS");
std::cout << "| HackersBeGone | Home Page | " << std::endl;
std::cout << "Threats = " << threats << std::endl; // Here is displays another random number when I
// need it to be the same number from main.cpp发布于 2020-04-06 07:32:44
您可以使用全局变量来执行此操作。尽管这不是最佳实践,但它是最简单的解决方案之一。将生成的随机数赋给该全局变量,并通过该变量重用它。
除此之外,您可以只使用与main中相同的srand种子。但这将是非正统的。
https://stackoverflow.com/questions/61050748
复制相似问题