0

我已经实现了自己tmpnam()的创建临时文件的功能。我使用以下定义来调整这个:

/* The length of random string. In /tmp/test143276 is 143246 */
#define RND_ROUND 6
/* Used as a minimal bound produced by number generator      */
#define RND_MIN 100000
/* Used as a maximum bound produced by number generator      */
#define RND_MAX 1000000

如您所见,真正需要的宏是RND_ROUND,而其他宏是传递给数字生成器的导数。生成公式为:

RND_MIN = 1 and [RND_ROUND-1] zeros
RND_MAX = 1 and [RND_ROUND] zeros

问题:如何创建一些在编译时生成RND_MINRND_MAX基于的宏?RND_ROUND

例子:

#define RND_ROUND 6
// somehow define those RND_MIN and RND_MAX
...
int32_t random = g_rand_int_range(generator, RND_MIN(RND_ROUND), RND_MAX(RND_ROUND));
4

3 回答 3

3

您可以使用电源功能来完成这项工作。

#define RND_MIN (pow (10, RND_ROUND-1))
#define RND_MAX (pow (10, RND_ROUND))

或者取决于传递的参数。

#define RND_MIN(val) (pow (10, (val)-1))
#define RND_MAX(val) (pow (10, (val)))
于 2013-07-29T08:44:25.240 回答
3

如果我是正确的,您可以使用电源功能:

#define RND_MIN(RND_ROUND)  pow(10, RND_ROUND - 1)
#define RND_MAX(RND_ROUND)  pow(10, RND_ROUND)

您可能想阅读:如何简化这个幂方程?

于 2013-07-29T08:45:04.163 回答
1

I would suggest you to forget about RND_ROUND: this is compile time, anyway!

#define RND_BASE 1000000
#define RND_MIN RND_BASE
#define RND_MAX (RND_BASE*10)

Now, if you really need RND_ROUND, RND_MIN and RND_MAX at compile time and not being expanded to pow, assuming your RND_ROUND is not you may branch it with #if (note that g_rand_int_range is limited to gint32, so RND_MAX<2^31=2'147'483'648<10^10 is possible):

#if RND_ROUND <= 1
#    define RND_MIN 1
#elif RND_ROUND <= 2
#    define RND_MIN 10
#elif RND_ROUND <= 3
#    define RND_MIN 100
#elif RND_ROUND <= 4
#    define RND_MIN 1000
#elif RND_ROUND <= 5
#    define RND_MIN 10000
#elif RND_ROUND <= 6
#    define RND_MIN 100000
#elif RND_ROUND <= 7
#    define RND_MIN 1000000
#elif RND_ROUND <= 8
#    define RND_MIN 10000000
#else
#    define RND_MIN 100000000
#endif

#define RND_MAX (RND_MIN*10)

This will also be safer, limiting RND_ROUND so that there will not be integer overflows.

于 2013-07-29T09:05:05.623 回答