(C++)使用函数的回文数


#include <iostream>
using namespace std;
bool pals(int n) {  

int remainder;
int reverse=0;

while(n>0){
remainder=n%10;
reverse=reverse*10+remainder;
n=n/10;     
}
return reverse;
}
int main() {
int nums;
cout<<"Input Desired Number: ";
cin >>nums;
if(pals(nums)) {
cout <<nums<<" palindrome";  
}
else {
cout <<nums<<" not a palindrome";
}
return 0;
}

不断返回";回文"但事实并非如此。

我的代码中是缺少什么还是出了什么问题。

任何关于未来参考的提示或指针都将是好的。非常感谢。

任何反馈都很棒!非常感谢。

您的问题是,您从函数中返回一个数字,并将其强制转换为布尔值,因此每个数字都将被截断为True值。

您应该在函数内部检查它是否是回文,并返回1/0结果,甚至更好的是返回布尔值。

关于所描述的行为的详细解释可以在以下链接中找到:

在C/C++中将int转换为bool

只在pals函数范围内执行int而不是bool在if条件下写入if(pals(nums(==nums({cout<lt;nums<lt"回文";}

最新更新