回文递归版本

时间:2018-09-26 21:09:35

标签: c++ recursion

我写了一个递归函数来查找一个单词是否是回文,但是我不明白为什么函数在递归结束时返回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;
    }
}  

2 个答案:

答案 0 :(得分:2)

因为您返回true,而不是递归调用的结果。更改为此:

return palindrome_recursive(word);

答案 1 :(得分:0)

在这里,无论true返回什么,您都将返回palindrome_recursive

palindrome_recursive(word);
return true;

将其更改为:

return palindrome_recursive(word);
相关问题