递归方法返回不需要的值
Recursive method returning undesired value
我有一个函数需要 return 完成某些操作后的值。我不会用细节来烦你。
我的函数调用自身,所以它是递归的。现在,我希望能够在从其他地方调用该函数时获得该函数的结果值。
所以这是代码:
public int compute(string[] myarray)
{
if (hasParantesisBlock)
{
// do stuff
// remove paranthesis block from myarray
String[] newArray = removeBlockFromArray(myarray);
// recursive call
compute(newArray);
}
else
{
// do other stuff obtaining a value
return value;
}
return 0; // if I remove this I get error
}
我这样称呼它:
int myval = compute(myStringArray);
我有一个字符串数组,我想从这个 myStringArray 中删除括号之间的块。我在我的函数计算中这样做,直到那里不再有括号块。当发生这种情况时,我想对字符串数组的元素进行计数(例如,这不是一个很好的例子)并且我想在主代码中 return 该值。
因为最后一个 "return 0; ",我总是收到 0。但是如果我从递归方法内部显示结果(值)...我得到正确的值。
如果我的字符串数组中有 2 个括号块,那么我将得到 2 个 returned 值零,如果我有 3 个块,那么我将得到 3 个零结果....
我不想要那些零结果。我只想return字符串数组中没有剩余块时获得的值。
所以步骤是这样的:
- does it have a block?
- yes. remove block and recall with changed array
- does it have a block?
- yes. remove block and recall with changed array
- does it have a block?
- no. RETURN my value (!!! this is the only return I want to receive)
- standard return
- standard return
我该怎么做?
正如彼得所说,
删除return 0; return compute(newArray) 的值代替。
(无法发表评论,因为我没有足够的代表)。
public int compute(string[] myarray)
{
if (hasParantesisBlock)
{
// do stuff
// remove paranthesis block from myarray
String[] newArray = removeBlockFromArray(myarray);
// recursive call
return compute(newArray);
}
else
{
// do other stuff obtaining a value
return value;
}
}
在不查看整个代码的情况下,我可以看到一些可能的问题。比如不使用方法中的return值。如
return compute(newArray)++;
我有一个函数需要 return 完成某些操作后的值。我不会用细节来烦你。 我的函数调用自身,所以它是递归的。现在,我希望能够在从其他地方调用该函数时获得该函数的结果值。 所以这是代码:
public int compute(string[] myarray)
{
if (hasParantesisBlock)
{
// do stuff
// remove paranthesis block from myarray
String[] newArray = removeBlockFromArray(myarray);
// recursive call
compute(newArray);
}
else
{
// do other stuff obtaining a value
return value;
}
return 0; // if I remove this I get error
}
我这样称呼它:
int myval = compute(myStringArray);
我有一个字符串数组,我想从这个 myStringArray 中删除括号之间的块。我在我的函数计算中这样做,直到那里不再有括号块。当发生这种情况时,我想对字符串数组的元素进行计数(例如,这不是一个很好的例子)并且我想在主代码中 return 该值。
因为最后一个 "return 0; ",我总是收到 0。但是如果我从递归方法内部显示结果(值)...我得到正确的值。
如果我的字符串数组中有 2 个括号块,那么我将得到 2 个 returned 值零,如果我有 3 个块,那么我将得到 3 个零结果....
我不想要那些零结果。我只想return字符串数组中没有剩余块时获得的值。
所以步骤是这样的:
- does it have a block?
- yes. remove block and recall with changed array
- does it have a block?
- yes. remove block and recall with changed array
- does it have a block?
- no. RETURN my value (!!! this is the only return I want to receive)
- standard return
- standard return
我该怎么做?
正如彼得所说,
删除return 0; return compute(newArray) 的值代替。
(无法发表评论,因为我没有足够的代表)。
public int compute(string[] myarray)
{
if (hasParantesisBlock)
{
// do stuff
// remove paranthesis block from myarray
String[] newArray = removeBlockFromArray(myarray);
// recursive call
return compute(newArray);
}
else
{
// do other stuff obtaining a value
return value;
}
}
在不查看整个代码的情况下,我可以看到一些可能的问题。比如不使用方法中的return值。如
return compute(newArray)++;