سؤال

/*
  david ballantyne
  10/10/13
  assesment lab 2
*/

//Libraries
#include <iostream>


//Global Constants

//Functioning Prototypes
using namespace std;

int main() {
         int n, num, digit, rev = 0;
         cout << "Enter a positive number"<<endl;
         cin >> num;
         num=n;

         do{
             digit = num%10;
             rev = (rev*10) + digit;
             num = num/10;

}
    while (num!=0);
         if (n == rev)
         cout << " The number is a palindrome"<<endl;
        else
         cout << " The number is not a palindrome"<<endl;
return 0;
}

I enter a palindrome and it keeps telling me it's not a palindrome, also if you could help me understand what kind of loop I would use to ask a "would you like to try again y/n" I'd be grateful.

هل كانت مفيدة؟

المحلول 2

cin >> num;
num=n;

assigns a user-specified integer to num then replaces it with the value of the uninitialised variable n

Did you mean to reverse the assignment

n=num;

instead?

also if you could help me understand what kind of loop I would use to ask a "would you like to try again y/n"

You could use a do...while loop with the condition for the while being calculated after you report whether the number was a palindrome.

نصائح أخرى

probably be easier to convert the number to a string. create a new string that is reverse order of the first string. And then compare to see if they are the same. Really no reason to do any real math, Palindromes are lexical, not mathematical.

#include <iostream>
using namespace std;

 int main()
{
  int userNum, palindrome[100], rem, rem2, count=0, count2=0, compare,  
   compare2;
  bool flag;

cout << "Enter number to test for Palindrome: ";
cin >> userNum;

compare = userNum;
compare2 = userNum;

// counting the digits in the number.
do {
    rem = compare % 10;
    count += 1;
    compare /= 10;
} while (compare >= 1);

// inputing in an array.
for (int i=0; i<count; i++)
{
    rem2 = compare2 % 10;
    palindrome[i] = rem2;
    compare2 /=10;
}

// Comparing array with palindrome.
for (int i=0; i < count; i++)
{
    if (palindrome[i] != palindrome[count-i-1])
        count2 = 1;
}

if (count2 == 1)
    cout << "Not a palindrome.";
else
    cout << "Palindrome\n";

return 0;




    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top