5 c++ random compiler-errors c++11
笔记:
这是代码:
#include <iostream>
#include <random>
#include <cstdlib>
#include <ctime>
#include <chrono>
int main() {
srand(time(0));
long long seed = rand();
std::default_random_engine rand_num(seed);
std::uniform_int_distribution<long long> range(0, 10);
long long a = range(rand_num);
long long b = rand_num();
std::cout<<seed<<"\n"; // the seed is different every time (tested)
std::cout<<a<<"\n";
std::cout<<b<<"\n";
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在我自己的计算机上运行代码时,带有 std::uniform_int_distribution (a) 的那个不是随机的,但可以正常工作并在在线 IDE 上创建一个随机数。
没有 std::uniform_int_distribution (b) 的那个适用于在线 IDE 和我自己的计算机。
有什么问题?我该如何解决?
更新:代码与 mt19937 引擎(std::mt19937 和 std::mt19937_64)一起工作正常
这似乎是 Windows 上 g++ 实现的一个已知问题。请参阅类似问题的已接受答案:Why do I get the sameequence for every run with std::random_device with mingw gcc4.8.1?
为了避免这个问题,您可以使用<chrono>工具来为随机数生成器提供种子:
#include <iostream>
#include <random>
#include <cstdlib>
#include <ctime>
#include <chrono>
int main() {
srand(time(0));
long long seed = rand();
std::default_random_engine rand_num{static_cast<long unsigned int>(std::chrono::high_resolution_clock::now().time_since_epoch().count())};
// ^ ^ ^ ^ ^ ^^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
std::uniform_int_distribution<long long> range{1,10};
long long a = range(rand_num);
long long b = rand_num();
std::cout<<seed<<"\n"; // the seed is different every time (tested)
std::cout<<a<<"\n";
std::cout<<b<<"\n";
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这在每次运行时都给了我不同的结果(在 Windows 上使用 g++)。
| 归档时间: |
|
| 查看次数: |
1404 次 |
| 最近记录: |