這是一個家庭作業問題。我無法轉換成如下遞歸函數:將循環轉換爲遞歸函數
public class Integrate {
public static double integrate(int a, int b, int steps)
{
double sum=0;
double delta = 1.0 * (b - a)/steps;
double x = a;
double f = 0.5*x*x + 3*x + 5;
for (int i = 0; i< steps; i++)
{
x = x + delta;
double fr = 0.5*x*x + 3*x + 5;
double area = f * delta + 0.5*(fr - f)*delta;
sum += area;
f = fr;
}
return sum;
}
public static void main(String [] args)
{
int a, b, step;
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
step = Integer.parseInt(args[2]);
System.out.format("Integral is %f\n", integrate(a,b,step));
}
}
這是我迄今爲止,但輸出是不一樣的原代碼。我無法弄清楚什麼是錯的
public class Integrate {
public static double integrate(int a, int b, int steps) {
double sum=0;
int i=0;
sum = rintegrate(a, b, steps, i, sum);
return sum;
}
public static double rintegrate(int a, int b, int steps,
int i, double sum) {
double delta = 1.0 * (b - a)/steps;
double x = a;
double f = 0.5*x*x + 3*x + 5;
if (i<steps) {
x = x + delta;
double fr = 0.5*x*x + 3*x + 5;
double area = f * delta + 0.5*(fr - f)*delta;
sum += area;
f = fr;
i++;
rintegrate(a, b, steps, i, sum);
}
return sum;
}
public static void main(String[] args) {
int a, b, step;
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
step = Integer.parseInt(args[2]);
System.out.format("Integral is %f\n", integrate(a,b,step));
}
}
什麼是你的原碼輸出?以及新代碼的輸出是什麼? – 2013-05-13 16:11:34
看起來你沒有使用你的'rintegrate'的遞歸值遞歸地... – 2013-05-13 16:12:10
a = 1,b = 10,step = 1000 .......原來出來360.000061和我的輸出0.076662 – user2378481 2013-05-13 16:15:30