我使用递归创建了一个C ++程序,它返回一个数字中的最大数字。 我按照自己的方式工作,但我找到了另一种选择:
int cifmax(int n) {
if(n <= 9)
return n;
return max(n % 10, cifmax(n / 10));
}
第二次返回如何工作?
您可以将此代码视为等效于以下更详细的版本:
int cifmax(int n) {
if (n <= 9){
return n; // trivial base case
} else {
int currentdigit = n % 10; // the least significant digit
int otherdigits = n / 10; // other digits past the least significant
int maxofotherdigits = cifmax(otherdigits); // make the recursive call
// compute maximum of the two
if (currentdigit > maxofotherdigits){
return currentdigit;
} else {
return maxofotherdigits;
}
}
}
请注意以下代码段:
if (currentdigit > maxofotherdigits){
return currentdigit;
} else {
return maxofotherdigits;
}
相当于:
return std::max(currentdigit, maxofotherdigits);
其中std::max返回其两个参数中较大的一个。