C++ 回文程序总是给出 0 (false) 作为输出问题;我的代码哪里错了?

标签 c++ function palindrome

问题是它总是输出 0 (false) 作为结果。问题可能出在 isPalindrome 函数中,但我无法确定确切位置。如果有人帮助,将不胜感激。

#include <iostream>
#include <cmath>
#include <string>
using namespace std;

bool isPalindrome(string word)
{
    bool result;

    for (int i = 0; i <= word.length() - 1; i++)
    {
        if (word.at(i) == word.length() - 1)
        {
            result = true;
        }
        else
        {
            result = false;
        }
        return result;
    }
}

int main()
{
    string word1;
    int count;
    cout << "How many words do you want to check whether they are palindromes: " << flush;
    cin >> count;

    for (int i = 0; i < count; i++)
    {
        cout << "Please enter a word: " << flush;
        cin >> word1;
        cout << "The word you entered: " << isPalindrome(word1);
    }
}

最佳答案

试试这个:

bool isPalindrome(string word)
{
    bool result = true;
    for (int i = 0; i < word.length() / 2; i++) //it is enough to iterate only the half of the word (since we take both from the front and from the back each time)
    {
        if (word[i] != word[word.length() - 1 - i]) //we compare left-most with right-most character (each time shifting index by 1 towards the center)
        {
            result = false;
            break;
        }  
    }    
    return result;
}

关于C++ 回文程序总是给出 0 (false) 作为输出问题;我的代码哪里错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58354303/

相关文章:

javascript - 比较两个数组之间的值

c++ - 想要获取perl在c、cpp或.h的多个文件中定义的函数名称

swift - 在 Swift 中声明函数类型的变量有什么意义?

python - 基本功能帮助-Python

c - 从函数返回结构变量而不创建中间变量的简写

java - 最小的回文数大于 N

C++ 将数组写入注册表中的二进制条目

c++ - 编辑框的最后一个字符位置

c++ - 在工作 GUI 示例中使用 Controller 和 QT Worker

algorithm - 这个 "compute all palindrome substrings"算法的运行时间是多少?