如何在程序开始时生成唯一的随机数,然后获取该数字并在函数中调用它

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

我正在用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
c++ random numbers stdio
1个回答
0
投票

您可以使用全局变量来执行此操作。尽管这不是最佳实践,但却是最简单的解决方案之一。将生成的随机数分配给该全局变量,然后通过该变量重用它。

除此之外,您可以只使用与主播相同的种子。但这将是非正统的。

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