将数字提高到x的幂后得到否定答案
我有这个代码,它在将一个数字提高到第 n 个数字后返回答案。
int getPower(int base, int x){
int result=1;
while (x != 0) {
result *= base;
--x;
}
return result;
}
我尝试测试 base 为 97 且 x 为 5 的位置。我得到了-2594335. 我尝试将结果的数据类型更改为 long,但仍然得到相同的负值。
回答
正如在对您的问题的评论中提到的那样,该类型的对象int可能不够大,无法存储此类值。所以用 typeint代替 type long long。
例如
#include <stdio.h>
long long int getPower( int base, unsigned int x )
{
long long int result = 1;
while ( x-- ) result *= base;
return result;
}
int main( void )
{
unsigned int x = 5;
int base = 97;
printf( "%d in the power of %u is %lldn", base, x, getPower( base, x ) );
}
程序输出是
97 in the power of 5 is 8587340257
而不是这个声明
printf( "%d in the power of %u is %lldn", base, x, getPower( base, x ) );
你可以写
long long int result = getPower( base, x );
printf( "%d in the power of %u is %lldn", base, x, result );
另一种方法是使用例如浮点类型long double而不是整数类型long long作为计算值的类型。