gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:33:33 24 4
gpt4 key购买 nike

问题是它总是输出 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com