一父阻、概念
二、代碼
#include <stdio.h>
int myPow(int base,int n);
int myPow2(int base,int n);
int main()
{
#pragma 1.涉及一個函數(shù) 用來計算B的n的次方
/*
b = 2
n = 3
int result = b(3);
b(0) = 1;
b(1) = b; == b(0) * b
b(2) = b * b; == b(1) * b
b(3) = b * b * b; == b(2) * b
b(n) = b(n -1) * b
2(3)
2 * 2 * 2;
result = 1 * 2
result = 2(result) * 2;
result = 2 * 2(result) * 2;
用上一次的結(jié)果 * 2
*/
int a = 2;
int b = 3;
// int result = myPow(a,b);
int result = myPow2(a, b);
printf("result = %i\n",result);
return 0;
}
#pragma mark for循環(huán)
int myPow(int base,int n)
{
// 1.定義變量保存計算結(jié)果
int result = 1;
for (int i = 0; i < n; i++) {
printf("%i * %i\n",result,base);
result = result * base;
}
return result;
}
#pragma mark 遞歸
/*
1.必須有一個明確的結(jié)束標(biāo)志
2.自己調(diào)用自己
*/
int myPow2(int base,int n)
{
int result = 1;
if (n <= 0) {
// 結(jié)束條件
return result;
}
else
{
return myPow2(base, n - 1) * base;
}
}
image.png