C ++ Palindrome程序始终将0(false)作为输出问题;我的代码在哪里错误?

问题描述 投票:1回答:2

问题是,它始终输出0(假)。问题可能出在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);
    }
}

c++ function palindrome
2个回答
0
投票

isPalindrome函数中的循环仅执行一次,因为return语句在循环的第一次迭代中无条件执行。我确信这不是故意的。

要确定字符串是否是回文,循环必须执行几次。只有在计算完最后一个字符之后(在循环的最后一次迭代中),才可以使用return语句。


0
投票

两个可能的问题。

您似乎正在将字符与数字进行比较

if (word.at(i) == word.length() - 1)

不是应该

if (word.at(i) == word.at(word.length() - 1))

if语句中有3个返回值,因此无论返回什么结果,返回给调用函数之前只比较一个字符。如果发现不匹配,则需要在循环之前将标志设置为true而不是false。循环结束后,返回标志。如果您正在寻找回文,您只需要将单词的前半部分与后半部分进行比较即可。

© www.soinside.com 2019 - 2024. All rights reserved.