目录
1、递归实现
程序完整代码
程序运行结果
2、非递归实现
程序完整代码
3、认识pow()函数
代码
1、递归实现
实现以下函数:计算并返回x^n的值
double factorial (double x, int n)
程序完整代码
#include<stdio.h>//double(double x, int n) // 计算并返回x^n的值double factorial(double x, double n){if (n == 0)return 1.0;else return (x* factorial(x, n-1));}int main(){double x = 1;int n = 1;scanf("%lf %d", &x, &n);if (n < 0)printf("%lf^%d=%lf\n",x,n, 1 / factorial(x, -n));elseprintf("%lf^%d=%lf\n",x,n, factorial(x, n));return 0;}
程序运行结果
2、非递归实现
程序完整代码
#include<stdio.h>int main(){int x, n;scanf("%d%d", &x, &n);double sum = 1;for (int i = 0; i < n; i++){sum *= x;}printf("%lf\n", sum);return 0;}
3、认识pow()函数
头文件:#include <math.h>
pow() 函数用来求 x 的 y 次幂(次方),x、y及函数值都是double型
其原型为:double pow(double x, double y);
pow(x,y):用来计算以x 为底的 y 次方值,然后将结果返回。
代码
#include<stdio.h>#include<math.h>int main(){int x, n;scanf("%d%d", &x, &n);double sum = pow(x, n);printf("%lf\n", sum);return 0;}
如果觉得《求X的N次方x^n(幂)递归和非递归和pow C语言初学》对你有帮助,请点赞、收藏,并留下你的观点哦!