C++ 生成大于32767的随机数
我正试图给一个变量指定一个介于0和65535之间的数字,但我不能,因为C++ 生成大于32767的随机数,c++,random,C++,Random,我正试图给一个变量指定一个介于0和65535之间的数字,但我不能,因为RAND_MAX被设置为32767。如何生成大于32767的随机数,同时生成的数字可能介于0和65535之间?我将尝试以下方法: int msb = (rand() % 2) << 15; int random = msb | rand(); #include <iostream> #include <random> int main() { std::random_device
RAND_MAX
被设置为32767。如何生成大于32767的随机数,同时生成的数字可能介于0和65535之间?我将尝试以下方法:
int msb = (rand() % 2) << 15;
int random = msb | rand();
#include <iostream>
#include <random>
int main()
{
std::random_device rd;
std::default_random_engine eng {rd()};
std::uniform_int_distribution<> dist(0, 65535);
for(unsigned i = 0; i < 10; ++i)
std::cout << dist(eng) << '\n';
}
int msb=(rand()%2)如果编译器支持C++11可以执行以下操作:
int msb = (rand() % 2) << 15;
int random = msb | rand();
#include <iostream>
#include <random>
int main()
{
std::random_device rd;
std::default_random_engine eng {rd()};
std::uniform_int_distribution<> dist(0, 65535);
for(unsigned i = 0; i < 10; ++i)
std::cout << dist(eng) << '\n';
}
使用C++11
函数。在@Brian之后,请阅读。如果int为32位,则移位后msb可能会大大大于65535。你的意思可能是short msb=rand(),你说得对。我必须屏蔽16个最高有效位才能达到预期效果。谢谢。两个问题。标准的rand()函数生成15位的随机数,从0到32767,如您所述。要将此范围扩展到65535,我们必须再添加一位。在第一行,我生成了一个介于0和1之间的随机数,即rand()%2。我明白了。但是,深入地说,为什么一个|操作符要执行+操作符的功能;为什么它能成功工作?你能在没有std的情况下修改语法吗?(当使用namespace std;)@user3273960时,我永远不会建议这样做:但它肯定会起作用。是的,这不是因为我想这样做,而是因为我需要使用namespace。问题:名称空间为:uniform_int_distribution dist(065535);保持这样?@user3273960是的,试试看,只需删除std::
限定符。@Galik,在C中也可以实现同样的事情吗?