【发布时间】:2014-06-01 18:10:06
【问题描述】:
我一直在寻找比我自己更好的解决方案,但我真的找不到一个我理解或适合我的解决方案。
我做了一个简单的游戏,计算机随机生成一个数字,然后你猜一个数字,如果它更高,计算机就会说更高等等..
问题是我随机生成的号码,在查找了很多关于<random>、uniform_int_distribution 和default_random_engine 的信息后。我发现计算机会生成一个随机数,但是如果你再次运行程序会生成相同的随机数。
我的解决方案:
uniform_int_distribution<unsigned> u(0,100); // code to randomly generate numbers between 0 and 100
default_random_engine e; // code to randomly generate numbers
size_t userInput; // User input to find out where to look in the vector
vector<int> randomNumbers; //vector to hold the random numbers
unsigned start = 0, ending = 101, cnt = 0; // used in the game not important right now
cout << "Please enter a number between 1 and 1000 for randomness" << endl;
cin >> userInput;
for(size_t i = 0; i < 1000; ++i){ //for loop to push numbers into the vector
randomNumbers.push_back(u(e));
}
unsigned guess = randomNumbers[userInput]; // finally the number that the user will have to guess in the game
我现在的解决方案是使用一个向量,将大量随机生成的数字推入其中,然后要求用户输入一个数字,然后计算机将其用于游戏。但是应该有更好的方法来做到这一点。因此我的问题是
有没有更好的方法来随机生成游戏中使用的数字?
【问题讨论】:
-
似乎与stackoverflow.com/questions/22105867/… 的主题相同。答案建议使用 std::default_random_engine engine(std::random_device{}());