Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

(C++) Palindrome Numbers using Function

#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;
}

Keeps returning " palindrome" when it isn't.

Is there something missing in my code or something wrong.

Any tips or pointers for future references would be good too. Thank you!

Any feedback is great! Thank You!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem is because you are returning a number from the function and casting it to a Boolean so every number will truncated to a True value.

You should check inside the function whether it’s a palindrome or not and return a 1/0 result or even better a Boolean value.

A thorough explanation on the behavior described can be found in the following link:

Casting int to bool in C/C++


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...