用C回文程序的不期望的输出++

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

于是,我开始学习C ++两个星期前,我想建立一个程序来检查,如果一个字符串是回文与否。我尝试不同的方法,包括其中str1以下列方式== str2的方法:

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

string empty;
string word;
bool inverse(string word)
{

    for (int i=0;i<=word.length();i++)
    {
         empty+=word[word.length()-i];
    }
    return empty==word;
}

int main()
{ 

    cout<<inverse("civic");

}

输出始终为0

方式二:在str1.compare(STR2)方法

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

string empty;
string word;
bool inverse(string word)
{

for (int i=0;i<=word.length();i++)
{empty+=word[word.length()-i];}

if (word.compare(empty))
return true;
else
return false;


}

int main()
{ 

if (inverse(word)==true)
cout<<"is a palindrome";
else
cout<<"is not a palindrome";
cout<<inverse("ano");
cout<<inverse("madam");
}

输出总是:是palindrome1(用1个或两个1在“回文”的端部),即使该字符串不是回文。

请向我解释我做了什么错误,我怎么能改正。另外,如果我想我的程序处理已在其空白的字符串,我该怎么办呢?

c++ string palindrome
3个回答
2
投票

有几个问题

  1. 您的代码是循环次数太多。例如三个字母应该循环三次一句话,但你的代码回路4(i=0i=1i=2i=3)。为了解决这个问题,你需要改变最终条件改用<<=
  2. 您是计算了错误的公式对称指数。例如,如果你有三个长度的字母词是word[0]word[1]word[2]。但是您的代码使用length - ii=0这将使用word[3]这是这个词所允许的范围之外。你需要使用的公式length - 1 - i而不是length - i做索引。

这两种错误是在编程相当普遍,他们是所谓的“减一”的错误。记住,总是仔细检查边界条件,当你写的代码,这样就可以从你的程序保持这样那样的错误了。


1
投票

对于第一个你需要改变

for (int i=0;i<=word.length();i++)
{empty+=word[word.length()-i];}

for (int i=0;i<word.length();i++)
{empty+=word[word.length()-(i+1)];}

0
投票

此行之后你的程序的行为将是不确定的:

for (int i = 0;i <= word.length(); i++)
    empty += word[word.length() - i];

由于长度始终是一个加最后一个元素(因为第一指数为零),当i0,则:word[word.length()]会给你最后一个元素之后的元素,这是不可能的,因此你的程序将调用因为C语言未定义行为/ C ++ ... word[word.length()]也可以当i本身变得word.length(),所以改变<=(小于或等于)到<(小于)

所以,它应该是:

for (int i = 0;i < word.length(); i++)
    empty += word[word.length() - 1 - i];
© www.soinside.com 2019 - 2024. All rights reserved.