问题描述
我有这段代码,它在将一个数字提升到第 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
类型的对象可能不够大,无法存储此类值。因此,将类型 int
替换为类型 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 %lld\n",base,x,getPower( base,x ) );
}
程序输出为
97 in the power of 5 is 8587340257
代替这个声明
printf( "%d in the power of %u is %lld\n",x ) );
你可以写
long long int result = getPower( base,x );
printf( "%d in the power of %u is %lld\n",result );
另一种方法是使用浮点类型 long double
而不是整数类型 long long
作为计算值的类型。