递归法:
#include<stdio.h>
int mi(int n, int k)
{if (k == 1) //如果是1次方{return n; //返回n的1次方(也就是n)}else{return n * mi(n, k - 1); //n*n的k-1次方}
}
int main()
{int n = 0, k = 0, sum = 0;printf("请输入n值和k值\n");scanf("%d%d", &n, &k);sum = mi(n, k);printf("%d的%d次方的值为%d\n", n, k, sum);return 0;
}
非递归法:
#include<stdio.h>
int mi(int n, int k)
{int i = 0, sum = 1; //sum的初始值要为1,不能为0,不然0*任何数还是0for (i = 0; i < k; i++) //循环k次{sum *= n; //每循环一次就*n,}return sum; //返回n的k次方的值
}
int main()
{int n = 0, k = 0, sum = 0;printf("请输入n值和k值\n");scanf("%d%d", &n, &k);sum = mi(n, k);printf("%d的%d次方的值为%d\n", n, k, sum);return 0;
}