《数据结构与算法分析 c语言描述》习题2.16
(编译环境 Microsoft Visual Studio 2019)
#include<stdio.h>
double pow(double x, unsigned int n);
int main(void)
{
unsigned int n;
double x;
printf("Please enter the base and exponent.\n");
scanf_s("%lf %d",&x, &n);
printf("Power value: %g\n", pow(x, n));
return 0;
}
double pow(double x, unsigned int n)
{
double temp = 1;
if (n == 0)
return 1;
while (n > 1)
{
if (n % 2 == 0)
{
x *= x;
n /= 2;
}
else
{
temp *= x;
x *= x;
n /= 2;
}
}
x *= temp;
return x;
}