本文介绍了mersenne_twister_engine类的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我一直在尝试使用c ++ 11 mersenne_twister_engine类( http://www.cplusplus .com / reference / random / mersenne_twister_engine / )在区间[0,1]中生成数字,但是我在每个数字上不断得到0。I have been trying to use the c++ 11 mersenne_twister_engine class( http://www.cplusplus.com/reference/random/mersenne_twister_engine/) to generate numbers in the interval [0,1] however I am continually getting 0 on every number.这是我的代码片段unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count(); std::mt19937 generator(seed1); for (int i=0; i < WIDTH * HEIGHT; i++) //GENERATES THE MATRIX OF CONNECTIVITY{ double random = generator()/generator.max(); if ( random > VERT_CONNECTIVITY ) vert_con[i] = 0; else vert_con[i] = 1;} generator )似乎是工作...它只是随机,给我0! generator() and generator.max() seem to be working... It is just random which gives me 0! 谢谢!推荐答案在C ++中, / 在整数上产生一个整数。例如11/2得到5,而不是5.5。同样, a / b 如果 a In C++, / on integer numbers results in an integer number. For example 11 / 2 results in 5, not 5.5. In the same way a / b is always zero if a < b.您的问题在这里:generator()/generator.max() 和 generator.max()都返回整数,当然, generator.max()> = generator ,因此结果为零(除非您非常幸运得到 max 数字,在这种情况下结果将是一个)。generator() and generator.max() both return integers and of course, generator.max() >= generator(), so the result is zero (unless you are very lucky to get the max number in which case the result would be one).要解决这个问题,您可以简单地转换:To fix this, you can simply cast it:(double)generator()/generator.max() 这篇关于mersenne_twister_engine类的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-12 15:37