【C語言】pow函式的模擬實現
阿新 • • 發佈:2021-01-26
技術標籤:c語言
函式介紹
pow(x,y) ——求x的y次方
函式模擬實現
普通版:遞減n的大小,逐次乘num
#include<stdio.h>
int my_pow(int num, int n)
{
if (n != 0)
return num * my_pow(num, n - 1);
else
return 1;
}
int main()
{
printf("%d\n", my_pow(2, 3));
return 0;
}
優化版:依據n的奇偶性來進行遞迴處理
#include<stdio.h>
int my_pow (int num, int n)
{
if (0 == n)
return 1;
else if (1 == n)
return num;
int tmp = my_pow(num, n / 2);//先儲存起來
if (0 == n % 2)//n為偶數的情況
return tmp * tmp;
else//n為奇數的情況
return num * tmp*tmp;
}
int main()
{
printf("%d\n", my_pow(2, 3));
return 0;
}
執行結果: