回文递归版本
Palindrome recursive version
我写了一个递归函数来查找一个单词是否是回文,但我不明白为什么函数在递归结束时返回一个 TRUE 值,而在此之前它打印 FALSE。
这是我的代码:
#include <iostream>
#include <string>
using namespace std;
bool palindrome_recursive(string word){
string::size_type wordLength = word.length();
if(wordLength == 0){
cout << "TRUE" <<endl;
return true;
}
if(word.at(0) != word.at(wordLength-1)){
cout << "FALSE" <<endl;
return false;
}
word.erase(wordLength-1);
word.erase(0,1);
cout << word << endl;
palindrome_recursive(word);
return true;
}
int main()
{
std::cout << "Enter a word: ";
std::string word;
std::cin >> word;
if(palindrome_recursive(word)){
std::cout << word << " is a palindrome" << std::endl;
} else {
std::cout << word << " is not a palindrome" << std::endl;
}
}
因为你返回true
,而不是递归调用的结果。将其更改为:
return palindrome_recursive(word);
在这里,无论palindrome_recursive
返回什么,您都会返回true
。
palindrome_recursive(word);
return true;
将其更改为:
return palindrome_recursive(word);
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 递归无序映射
- TSP递归解的迭代形式
- 如何在Elixir中调用递归函数并行
- 回文递归版本
- c 字符串 c++ 中 strlen 的递归版本
- 如何从非递归版本定义斐波那契函数
- "find"的递归版本和非递归版本有什么区别?
- Python 3.3 如何将这个递归函数转换为纯收益循环版本?
- 尝试使用C++实现检测字符串中回文的递归版本.在这里遇到了一些麻烦
- 调用原始版本的DLL挂钩函数时,我得到了无限递归
- 为什么这个函数的递归版本更快
- 为什么函数的递归版本会比C中的迭代版本快