Saturday, May 22, 2010

C++: Help with putting an extracted number back together?

Here is my program that finds out if an inputted number is a palindrome or not:





#include %26lt;iostream%26gt;


using namespace std;





int main()


{


cout %26lt;%26lt; "Enter a five-digit integer: " %26lt;%26lt; endl;


int num;


cin %26gt;%26gt; num;





int fifth = num % 10;


num = num / 10;





int fourth = num % 10;


num = num / 10;





int third = num % 10;


num = num / 10;





int second = num % 10;


num = num / 10;





int first = num % 10;


num = num / 10;





if (first == fifth %26amp;%26amp; second == fourth)


cout %26lt;%26lt; num %26lt;%26lt; " is a palindrome" %26lt;%26lt; endl;


else


cout %26lt;%26lt; num %26lt;%26lt; " is not a palindrome" %26lt;%26lt; endl;





return 0;


}





All of my results are correct except for when I try to print out the original inputted number as a whole again. How do I do this? I keep getting 0.





I appreciate your help! ^_^

C++: Help with putting an extracted number back together?
You're storing the number in the "num" variable, but then you're repeatedly dividing num by 10 while determining whether or not it's a palindrome. In other words, you're destroying the value in num as you go along.





To fix this store a temporary copy of num in another variable (e.g. "original_num") at the start of the program and print that variable instead. Either that or print the value of num before you start changing it.





(BTW, it won't work if you try to restore the value of num by repeatedly multiplying it back out by 10 a few times. Every time you divide an integer variable the remainder is discarded.)
Reply:It is because





the original input getting change when you do the following





num = num / 10;





insted of that execute the following code it will work





#include %26lt;iostream%26gt;


using namespace std;





int main()


{


cout %26lt;%26lt; "Enter a five-digit integer: " %26lt;%26lt; endl;


int num,num1;


cin %26gt;%26gt; num;


num1=num;


int fifth = num % 10;


num = num / 10;





int fourth = num % 10;


num = num / 10;





int third = num % 10;


num = num / 10;





int second = num % 10;


num = num / 10;





int first = num % 10;


num = num / 10;





if (first == fifth %26amp;%26amp; second == fourth)


cout %26lt;%26lt; num1 %26lt;%26lt; " is a palindrome" %26lt;%26lt; endl;


else


cout %26lt;%26lt; num1 %26lt;%26lt; " is not a palindrome" %26lt;%26lt; endl;





return 0;


}
Reply:You are changing the original number as the program runs.


Save the original number in another variable and then print that out.


No comments:

Post a Comment