Bool函数总是返回false

Bool function always returning false

本文关键字:返回 false 函数 Bool      更新时间:2023-10-16

嗨,我正在尝试创建一个函数,让用户知道输入的单词是否是回文(相同的单词是否反过来拼写,例如:kayak)。这是我想出来的函数,但由于某种原因,函数总是返回false。

#include <iostream>
#include <cctype>
using namespace std;
bool compare(string str2)
{
    int first = 0, mid, last = (str2.size() - 1);
    while(first < last)
    {
        if(first == last)
        {
            first++;
            last--;
        }
        else return(false);
    }
    return(true);  
}
int main()
{
    string pal;
    cout <<"Enter your single word palindrome: ";
    getline(cin,pal);
    if(compare(pal) == true)cout << pal <<" is a palindrome.n";
    else                    cout << pal <<" is not a palindrome.n";
    return(0);
}

你实际上没有做任何字符比较,只是比较索引firstlast -它们不匹配,所以你返回false。

按照下面的代码,如果我们假设last大于0,while(first < last)true, if(first == last)false,因此函数返回false。我猜你可能想比较字符而不是索引。

int first = 0, mid, last = (str2.size() - 1);
while(first < last)
{
    if(first == last)
    {
        first++;
        last--;
    }
    else return(false);
}

if (first == last) {}这是误差。

在您的代码中,应该比较char而不是int。所以试试这个:

bool compare(string str2)
{
    int first = 0, mid, last = (str2.size() - 1);
    while(first] < last)
    {
        if(str2[first] == str2[last])
        {
            first++;
            last--;
        }
        else 
            return(false);
    }
    return(true);  
}