刚从 Python 切换到 C++,我开始用 C++ 重写我的 Python 工具以更好地理解,但无法解决这个问题...
此函数将生成随机数的范围,例如“randomRange(12)”可能会返回 12 个数字的范围,如“823547896545”
python :
def randomRange(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
number = randomRange(12)
C++:
int n;
int randomRange(n){
int range_start = ?
int range_end = ?
int result = ?(range_start, range_end);
return (result);
};
int number = randomRange(12);
我找不到问号“?”的等价物
最佳答案
如果 n 值高,您将难以获得良好的随机性,但是:
#include <math.h> // for pow()
#include <stdlib.h> // for drand48()
long randomRange(int n)
{
// our method needs start and size of the range rather
// than start and end.
long range_start = pow(10,n-1);
long range_size = pow(10,n)-range_start;
// we expect the rand48 functions to offer more randomness
// than the more-well-known rand() function. drand48()
// gives you a double-precision float in 0.0-1.0, so we
// scale up by range_size and and to the start of the range.
return range_start + long(drand48() * range_size);
};
这是另一种方法。在 32 位平台上,你只能在 int 中做 9 位数字,所以我们让函数返回一个 double,并生成一串 ASCII 数字然后转换:
#include <math.h> // for pow()
#include <stdlib.h> // for atof()
// arbitrary limit
const int MAX_DIGITS = 24;
double randomRange(int n)
{
char bigNumString[ MAX_DIGITS+1 ];
if (n > MAX_DIGITS)
{
return 0;
}
// first digit is 1-9
bigNumString[0] = "123456789"[rand()%9];
for (int i = 1; i < n; i++)
{
// subsequent digits can be zero
bigNumString[i] = "0123456789"[rand()%10];
}
// terminate the string
bigNumString[i] = 0;
// convert it to float
return atof(bigNumString);
};
关于c++ - 等效于 C++ 中的这个 Python 随机数生成器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7324285/