
有2种方法可以选择:
直接调用库函数,如 Java 中的 math下 power 的方法, Javascript也有类似函数
自己手写考虑的点
溢出处理
没定义的情况,比如0^0(零的零次方)
特殊情况(任意数的0次方)
n为负数的情况
n为正数
#include
<stdioh>
//
递归函数计算x的n次幂,这里都是用的int,因此计算范围只能限制在int类型的取值范围下
//
如果需要计算更大的值,需要将类型修改为float
int
mypow(int
x,
int
n)
{
if
(n
<=
0)
return
1;
else
return
x
mypow(x,
n
-
1);
}
int
main()
{
printf("2^32
=
%d\n",
mypow(2,
10));
//
计算2的10次方
return
0;
}
//文件1 powc
#include"linkinh"
float mypow(float x, int n)
{
float result = 1;
for(int i = 0;i < n; i++)
result = x;
return result;
}
//文件2 printc
#include<stdioh>
#include"linkinh"
void print(float c){printf("%f",c);}
//文件3 insertc
#include<stdioh>
#include"linkinh"
float insert(void)
{
float x;
scanf("%f",&x);
return x;
}
int insert(void)
{
int x;
scanf("%d",&x);
return x;
}
//文件4 linkinh
float mypow(float x, int n);
void print(float c);
float insert(void);
int insert(void);
//文件5 mainc
include"linkinh"
int main()
{
float x;
int n;
x = insert();
n = insert();
print(mypow(x,n));
return 0;
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)