C++ 64 位整数运算:有人可以解释为什么这个有效而另一个无效吗?
我需要对 64 位整数进行操作。我试图将 36 的结果提高到 12 次方作为练习(并且作为要求)。
我在 VS2008 编译器上使用了 unsigned long long 来表示 64 位整数。我编写了下面的代码,有人可以向我解释一下,为什么我的 for 循环版本会产生错误的结果,而我的 Power 函数的递归版本会产生正确的结果?
仅供参考:36 提高到 12 是 4738381338321616896
template< typename _T1, typename _T2 >
_T1 Power( _T1 p_base, _T2 p_power )
{
/*
// This produces 0?!!
if( p_power == 0 ) return 1;
for( _T2 i = 1; i < p_power; ++i )
{
p_base *= p_base;
}
return p_base;
*/
// This produces correct result.
if( p_power == 0 ) return 1;
if( p_power == 1 ) return p_base;
return p_base * Power( p_base, p_power - 1 );
}
void main( int argc, char * argv[] )
{
unsigned long long charsetSize = 36LL;
printf( "Maximum Keys: %llu\n\n", Power( charsetSize, 12 ) );
system( "pause" );
}
I need to operate on 64bit integers. I am trying to get the result of 36 raised to the power of 12 as an exercise (and as a requirement).
I've used unsigned long long for 64 bit integer on my VS2008 compiler. I've made the code below and can someone explain to me, why my for loop version produces incorrect results while my recursive version of the Power function produces correct result?
FYI: 36 raised to 12 is 4738381338321616896
template< typename _T1, typename _T2 >
_T1 Power( _T1 p_base, _T2 p_power )
{
/*
// This produces 0?!!
if( p_power == 0 ) return 1;
for( _T2 i = 1; i < p_power; ++i )
{
p_base *= p_base;
}
return p_base;
*/
// This produces correct result.
if( p_power == 0 ) return 1;
if( p_power == 1 ) return p_base;
return p_base * Power( p_base, p_power - 1 );
}
void main( int argc, char * argv[] )
{
unsigned long long charsetSize = 36LL;
printf( "Maximum Keys: %llu\n\n", Power( charsetSize, 12 ) );
system( "pause" );
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在每次迭代时对结果进行平方。它应该类似于:
请注意,如果您像这样编写循环,则不需要
p_power == 0
检查。You're squaring the result at each iteration. It should be something like:
Note that if you write the loop like this, the
p_power == 0
check is unnecessary.这是因为您将每次乘法的结果存储在 p_base 中。这可能导致变量溢出。
您需要分别存储 p_base 和“工作”变量的输入值。根据for循环的逻辑,2的4次方是65536。
This is because you are storing the result of each multiplication in p_base. This is probably causing the variable to overflow.
You need to store the input value for p_base and the "working" variable separately. By the for loop's logic, 2 to the power of 4 is 65536.
这是不正确的。每次迭代后结果都会平方
Correction
This is incorrect. The result gets squared after each iteration
Correction