Bool 函数总是返回 false
Bool function always returning false
您好,我正在尝试创建一个功能,让用户知道输入的单词是否为回文(相同的反向拼写,例如:kayak)。这是我想出的函数,但由于某种原因,该函数总是 return 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);
}
您实际上并没有进行任何字符比较,只是比较索引 first
和 last
- 它们不匹配,所以您 return false。
如果(第一个 == 最后一个){ }
这是错误。
按照下面的代码,如果我们假设 last
大于 0,则 while(first < last)
是 true
,然后 if(first == last)
是 false
,因此函数 returns false
。我猜您可能想要比较字符而不是索引。
int first = 0, mid, last = (str2.size() - 1);
while(first < last)
{
if(first == last)
{
first++;
last--;
}
else return(false);
}
在您的代码中,您应该比较 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);
}
您好,我正在尝试创建一个功能,让用户知道输入的单词是否为回文(相同的反向拼写,例如:kayak)。这是我想出的函数,但由于某种原因,该函数总是 return 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);
}
您实际上并没有进行任何字符比较,只是比较索引 first
和 last
- 它们不匹配,所以您 return false。
如果(第一个 == 最后一个){ } 这是错误。
按照下面的代码,如果我们假设 last
大于 0,则 while(first < last)
是 true
,然后 if(first == last)
是 false
,因此函数 returns false
。我猜您可能想要比较字符而不是索引。
int first = 0, mid, last = (str2.size() - 1);
while(first < last)
{
if(first == last)
{
first++;
last--;
}
else return(false);
}
在您的代码中,您应该比较 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);
}