【发布时间】:2019-10-12 12:45:40
【问题描述】:
问题是它总是输出 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);
}
}
【问题讨论】:
-
你对这一行的意图是什么:if (word.at(i) == word.length() - 1)
-
另外:试着逐行分析这个问题。使用调试器,这样您就可以准确地看到问题出在哪里。
-
检查位置0的字母是否与最后一个位置的字母相同。然后继续检查位置 1 和位置 - 2 的字母,依此类推。
-
word.length -1 不返回字母。同样,通过返回 true 或 false,您不会继续循环而是退出函数,因此这永远不会起作用。
-
您建议使用哪一行代码来检查第一个和最后一个字母等等,直到您检查所有这些并确定它是否是回文?跨度>
标签: c++ function palindrome