简体   繁体   中英

Palindrome recursive version

I have written a recursive function to find whether a word is palindrome or not, but I don't understand why function returns a TRUE value at the end of recursion while it prints FALSE before that.

here is my code:

#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;
    }
}  

Because you return true , not the result of the recursive call. Change it to this:

return palindrome_recursive(word);

Here, you are returning true regardless of what palindrome_recursive returns.

palindrome_recursive(word);
return true;

Change it to:

return palindrome_recursive(word);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM