c语言快速幂运算代码(要求该代码还可以正确处理负数次幂和零次幂的情况)
时间: 2024-05-06 17:21:12 浏览: 45
以下是处理正数次幂和零次幂的C语言快速幂运算代码:
```C
#include <stdio.h>
double power(double x, int n){
if(n==0) return 1;
double half = power(x, n/2);
if(n%2==0) return half*half;
else return half*half*x;
}
int main(){
double x;
int n;
printf("Input x and n: ");
scanf("%lf %d", &x, &n);
double ans = power(x, n);
printf("%.3lf ^ %d = %.3lf\n", x, n, ans);
return 0;
}
```
如果要处理负数次幂,可以考虑以下修改:
```C
#include <stdio.h>
double power(double x, int n){
if(n==0) return 1;
double half = power(x, n/2);
if(n%2==0) return half*half;
else if(n>0) return half*half*x;
else return half*half / x;
}
int main(){
double x;
int n;
printf("Input x and n: ");
scanf("%lf %d", &x, &n);
double ans = power(x, n);
printf("%.3lf ^ %d = %.3lf\n", x, n, ans);
return 0;
}
```
此时,函数可以正确处理负数次幂和零次幂的情况。
阅读全文