Java 递归编程
我仍在学习,似乎无法将我的头脑集中在看似简单的任务上。 computeMethods方法是im完全难倒的地方,然而反向方法我只是不断地返回相同的整数,而没有反向Java 递归编程,java,recursion,Java,Recursion,我仍在学习,似乎无法将我的头脑集中在看似简单的任务上。 computeMethods方法是im完全难倒的地方,然而反向方法我只是不断地返回相同的整数,而没有反向 /**************************** * For Method Computemethods1 i must compute series * b(x)=1/3+2/5+3/7..... +x/2x+1 * For method ComputeMethod2
/****************************
* For Method Computemethods1 i must compute series
* b(x)=1/3+2/5+3/7..... +x/2x+1
* For method ComputeMethod2
* 1/2+2/3+......... x/(x+1)
*******************************/
public static int computeMethod1(int x){
if (x==0)
return 0;
if (x==1)
return 1;
return computeMethod1(x-1/3/(x-1))+computeMethod1(x-2/3/(x-2));
}
public static int computeMethod2(int x){
if (x==0)
return 0;
return computeMethod2((x-1)/(x-1)+1)+computeMethod2((x-2)/(x-2)+1);
}
/********************
* For method reverseMethod i must reverse a user given int
**********************/
public static int reverseMethod(int x){
int reversedNum=0;
if (x!=0)
return x;
reversedNum=reversedNum *10 +x%10;
return reversedNum+reverseMethod(x/10);
}
/******************
* For method sumDigits i must use recursion
* to sum up each individual number within the int
********************/
public static long sumDigits(long n){
if( n==0)
return 0;
if (n==1)
return 1;
else
return n+sumDigits(n-1);
}
}
对于反向方法,您使用:
如果(x!=0)返回x代码>
可能需要使用:如果(x==0)返回x
。所以逻辑是,如果给定的参数是0,那么返回0,否则返回倒数
注意:正如comentaries中提到的,请注意类型,因此对于除法,您最好使用float
或double
,并注意操作优先级以获得正确的结果,因此(x+1)/2
将不同于x+1/2
,按照你的小x代码
例如,computeMethod1
应返回:
1/3
用于x==1
,而此时它只返回1
(注意,返回类型需要是int
以外的内容)
1/3+2/5
用于x==2
1/3+2/5+3/7
对于x==3
对于每个x
,请注意我们如何使用前面的结果,即computeMethod1(x-1)
当你遇到似乎没有达到预期效果的代码时,让代码变得越来越简单,直到你能缩小问题的范围,然后希望问题是什么,或者在线文档可以告诉你。x-1/3
可能是整数除法的问题?尝试使用float
或double
数字,即x-1./3。
也相应地更改方法的参数。另外,您的sumdights
似乎有点不对劲。。。事实上,这更像是“从1到n的所有数字之和”。你的问题是什么?您应该具体说明哪些不符合预期。另外,请删除不相关的代码。