K&R《C语言编程》第26页 函数问题
我写了如下的代码:
程序代码:#include <stdio.h>
int power(int m, int n);
/* test power function */
int main(int argc, const char * argv[])
{
int i;
for (i=0; i<10; ++i)
printf("the power of 2 by %d is %d \n", i, power(2,i) );
printf("the power of -3 by %d is %d \n", i, power(-3,i));
return 0;
}
/* power function: raise base to n-th power; n>=0 */
int power(int base, int n)
{
int i, p;
p=1;
for (i=1; i<=n; ++i)
p = p * base;
return p;
}但却得到如下结果:
程序代码:the power of 2 by 0 is 1 the power of 2 by 1 is 2 the power of 2 by 2 is 4 the power of 2 by 3 is 8 the power of 2 by 4 is 16 the power of 2 by 5 is 32 the power of 2 by 6 is 64 the power of 2 by 7 is 128 the power of 2 by 8 is 256 the power of 2 by 9 is 512 the power of -3 by 10 is 59049
而我期待的结果是:
程序代码:the power of 2 by 0 is 1 the power of -3 by 0 is 1 the power of 2 by 1 is 2 the power of -3 by 1 is -3 the power of 2 by 2 is 4 the power of -3 by 2 is 9 the power of 2 by 3 is 8 the power of -3 by 3 is -27 the power of 2 by 4 is 16 the power of -3 by 4 is 81 the power of 2 by 5 is 32 the power of -3 by 5 is -243 the power of 2 by 6 is 64 the power of -3 by 6 is 729 the power of 2 by 7 is 128 the power of -3 by 7 is -2187 the power of 2 by 8 is 256 the power of -3 by 8 is 6561 the power of 2 by 9 is 512 the power of -3 by 9 is -19683
请教我的代码在哪里写错了呢?
谢谢!








