c++我的随机生成器随机生成某些东西,但是每次运行它时它都以相同的顺序执行
所以我做了一个MAC地址生成器。但是随机部分很奇怪。它随机生成一个数字,我用来从数组中选择一些东西。但是每次运行exe。它生成相同的数字。这是我的代码
#include <random>
#include <string>
//Mac Addr example -> 82-F5-4D-72-C1-EA
//6 two char sets
//Dont include spaces/dashes/dots
std::string chars[] = { "A","B","C","D","E","F" };
int nums[] = { 0,1,2,3,4,5,6,7,8,9 };
std::string GenMacAddr()
{
std::string final;
std::string CharSet;
int choice;
for (int i = 0; i < 6; i++) {
choice = 1 + rand() % 4;
if (choice == 1) { //Char Set only int
for (int x = 0; x < 2; x++) { //Makes action happen twice
final += std::to_string(nums[rand()%10]);
}
}
else if (choice == 2) { //Char set only str
for (int x = 0; x < 2; x++) { //Makes action happen twice
final += chars[rand() % 6];
}
}
else if (choice == 3) {
final += chars[rand() % 6];
final += std::to_string(nums[rand() % 10]);
}
else if (choice == 4) {
final += std::to_string(nums[rand() % 10]);
final += chars[rand() % 6] ;
}
}
return final;
}
回答
rand() 是一个确定性随机数生成器。为了获得实际的伪随机结果,您应该首先使用类似srand(time(NULL)).
如果你环顾四周,你会发现这是一个糟糕的方法,你应该完全放弃 rand() ,而是使用<random>C++11 。Stephan T. Lavavej 有一个非常好的演讲,你应该在这里看到它。
这也是他从那次演讲中推荐的代码片段。
#include <random>
#include <iostream>
int main() {
std::random_device random_dev; // Non deterministic random number generator
std::mt19937 mers_t(random_dev()); // Seed mersenne twister with it .
std::uniform_int_distribution<int> distribution(0, 100); // Bound the output.
// Print a random integer in the range [0,100] ( included ) .
std::cout << distribution(mers_t) << 'n';
}
- Note that `std::random_device` isn't required to be non-deterministic. It should be if possible but it is not required to.
- being deterministic isnt *the big* disadvantage `rand()`, often this is a very desirable feature, its also not the reason `rand()` is discouraged
THE END
二维码