根据牛顿迭代法参照网上一些代码 写了一个可以对任意整数开任意次方的东东 送给大家作为新年礼物
程序代码:
因为不想使用math.h这个头文件 所以自己写了几个函数
#include <stdio.h>
#define zero 0.000001
double mypow(double x,int n)
{
if(n==0) return 1.0;
double t=1.0;
for(;n>0;t*=x,n--);
return t;
}
int searchroot(double x,int n)
{
int t=1;
while(1)
{
if (mypow(t,n)-x<=zero && mypow(t+1,n)-x>=zero) return t;
t++;
}
return t;
}
double myfabs(double m,double n)
{
double t=m-n;
if(t>0) return t;else return t*(-1);
}
double rooting(double x,int n)
{
int root=searchroot(x,n);
double x1=(double)root;
double x0,f0,f1;
do
{
x0=x1;
f0=mypow(x0,n)-x;
f1=n*mypow(x0,n-1);
x1=x0-f0/f1;
}while(myfabs(x0,x1)>=zero);
return x1;
}
int main()
{
double x=88888888;
int n=2;
for(;n<8;printf("对%12.0f进行开%d次方结果是%12.6f\n",x,n-1,rooting(x,n),n++));
n=2;
for(;n<8;printf("验证%12.6f的%d次方=%12.6f\n",rooting(x,n),n-1,mypow(rooting(x,n),n),n++));
return 0;
}
程序代码:这是样例输出: 对 88888888进行开2次方结果是 9428.090369 对 88888888进行开3次方结果是 446.288632 对 88888888进行开4次方结果是 97.098354 对 88888888进行开5次方结果是 38.883871 对 88888888进行开6次方结果是 21.125545 对 88888888进行开7次方结果是 13.663112 验证 9428.090369的2次方=88888888.000000 验证 446.288632的3次方=88888888.000000 验证 97.098354的4次方=88888888.000000 验证 38.883871的5次方=88888888.000000 验证 21.125545的6次方=88888888.000001 验证 13.663112的7次方=88888888.000000
[ 本帖最后由 wp231957 于 2014-2-3 16:03 编辑 ]










新年快乐!~