可以通过循环或递归的方式来实现。下面是两种实现方式:
- 循环实现:#include <stdio.h>
double power(double base, int exponent) {
double result = 1.0;
int i;
if (exponent < 0) {
printf("Exponent should be non-negative.\n");
return 0.0;
}
for (i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
int main() {
double base;
int exponent;
printf("Enter the base: ");
scanf("%lf", &base);
printf("Enter the exponent: ");
scanf("%d", &exponent);
double result = power(base, exponent);
printf("Result: %.2lf\n", result);
return 0;
}
- 递归实现:#include <stdio.h>
double power(double base, int exponent) {
if (exponent == 0) {
return 1.0;
}
if (exponent < 0) {
printf("Exponent should be non-negative.\n");
return 0.0;
}
return base * power(base, exponent - 1);
}
int main() {
double base;
int exponent;
printf("Enter the base: ");
scanf("%lf", &base);
printf("Enter the exponent: ");
scanf("%d", &exponent);
double result = power(base, exponent);
printf("Result: %.2lf\n", result);
return 0;
}
这两种实现方式都可以用来计算平方求幂,循环实现适用于较小的指数,而递归实现适用于较大的指数。