我有这段代码:
public static void main(String args[]){
int e[]={1,2,3};
int f[]={1,2,3};
int t=e.length-1;
System.out.println(Recursivo6(e,f,t));
}
public static boolean Recursivo6(int e[], int f[], int t){
if(t==0) {
if((e[0]==f[0]) && Recursivo6(e, f, t-1)){
return true;
}
}
return false;
}
但是在方法recursivo中,第一个条件不起作用,它总是抛弃我的假,你能帮助我吗?感谢。
答案 0 :(得分:1)
它返回false,因为条件是(t == 0),而t是数组的长度,所以它总是返回false。也许尝试if(t> 0)
答案 1 :(得分:0)
看看以下单行:
public static boolean Recursivo6(int e[], int f[], int t){
return ((e[t] == f[t]) && ((t == 0) || (Recursivo6(e, f, t - 1))));
}
它始于t
位于数组的末尾。在每次迭代中,如果数组的元素在相应的索引处不相等,那么&&
的第二个操作数将不会被评估,因此,这部分非常高效。 &&
的第二个操作数是一个逻辑表达式,如果我们位于算法的末尾,则计算结果为true
,该算法由t
0
签名。如果t
到达0
,将不再调用Recursivo6
。否则,使用递减的t
来调用它。
你的错误:
if
作为初始false
值0
始终为t
t
'元素而不是0
'