Bool函数总是返回false
Bool function always returning false
嗨,我正在尝试创建一个函数,让用户知道输入的单词是否是回文(相同的单词是否反过来拼写,例如: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);
}
你实际上没有做任何字符比较,只是比较索引first
和last
-它们不匹配,所以你返回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);
}
相关文章:
- QueryWorkingSet总是返回false
- 当返回类型声明为 ListNode 时,我们是否可以返回 false<T>*
- 等于在 c++ 中返回 false
- strcmp 对于相等的字符序列返回 false
- C++ - 负数和正数之间的比较返回 false
- protobuf 的 ParseFromString 函数返回 false
- 递归函数始终返回 false
- 为什么 GetExitCodeThread() 在这里返回 FALSE?
- MFC 的 OnInit() 函数中的返回 true 和返回 false 有什么区别
- if 语句在条件为真时返回 false
- 为什么 std::isnan() 对于具有 NAN 值的双变量返回 false
- is_lock_free() 在升级到 MacPorts gcc 7.3 后返回 false
- 在 winapi 回调函数上返回 FALSE 时出现意外行为(循环被跳过?
- 如果数组中有重复的数字,如何返回'false'?
- std::is_array 当它应该返回 false 时返回 true
- 为什么pyarg_parsetuple总是返回false
- 删除为应该在哈希表中的记录返回 false 的函数
- Vulkan 和 glfwVulkanSupported() 总是返回 false
- tf2_ros::Buffer::canTransform() 为现有转换返回 False
- 出于某种原因,布尔值返回 false