只需从Python切换到C++,我开始用C++重新编写我的Python工具以便更好地理解,但无法解决这个问题......
此函数将生成随机数范围,例如"randomRange(12)"可返回12个数字的范围,如"823547896545"
蟒蛇:
def randomRange(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
number = randomRange(12)
Run Code Online (Sandbox Code Playgroud)
C++:
int n;
int randomRange(n){
int range_start = ?
int range_end = ?
int result = ?(range_start, range_end);
return (result);
};
int number = randomRange(12);
Run Code Online (Sandbox Code Playgroud)
我找不到相应的问号"?"
当 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);
};
Run Code Online (Sandbox Code Playgroud)
这是另一种方法。在 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);
};
Run Code Online (Sandbox Code Playgroud)