函数头为double power(double x,int n)。在主函数中输入x、n并调用该函数求 (函数定义在主函数后面,在调用前做函数声明)
输出x^n
1 #define _CRT_SECURE_NO_WARNINGS 1 2 #include<stdio.h> 3 double power(double, int); 4 int main() 5 { 6 double x; int n; 7 puts("INPUT 'x', 'n'\n"); 8 scanf("%lf%d", &x, &n); 9 printf("x^n = %lf", power(x, n)); 10 return 0; 11 } 12 double power(double x, int n) 13 { 14 int i; double rst = 1; 15 if (n == 0)//i不会小于0 16 { 17 return 1; 18 } 19 else 20 for (i = 1; i <= n; i++)//常规思路 21 { 22 rst = rst * x; 23 } 24 return rst; 25 }
1 double power(double x, int n)//用递归 2 { 3 int i; double rst = 1; 4 if (n == 0) return 1; 5 else return x * power(x, n - 1); 6 }