要求:
http://codeup.cn/problem.php?cid=100000588&pid=10
说明:
特别把这一题拿出来,这一题用递归很容易实现,but,第一次写的这个代码,没有用一个中间变量,导致超时了。。
这是超时的代码:
#include <stdio.h>
#include <math.h>
double F(int a,int b,double x){
if(b == 0){
x = (double)a;
}
else{
b = b - 1;
x = F(a,b,x)*2/3 + a/(3*F(a,b,x)*F(a,b,x));
}
return x;
}
int main(){
int a,n;
while(scanf("%d %d",&a,&n) != EOF){
double t = 0;
printf("%.6f\n",F(a,n,t));
}
return 0;
}
这是修改后的代码:
#include <stdio.h>
#include <math.h>
double a,x;
double F(double a,int b,double x){
if(b == 0){
x = a;
}
else{
double temp = F(a,b-1,x);//这种效率明显比写多个 F(a,b-1,x)效率要高!!!
x = temp*(2.0/3.0) + a/(3*temp*temp);
}
return x;
}
int main(){
int n;
while(scanf("%lf %d",&a,&n) != EOF){
printf("%.6f\n",F(a,n,x));
}
return 0;
}