检查数字是否是C ++中的回文

时间:2013-10-10 16:57:48

标签: c++ qt loops math palindrome

/*
  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;
}

我进入了一个回文并且它一直告诉我它不是回文,如果你能帮助我理解我会用什么样的循环来问“你想再试一次y / n”我会感激不尽。

3 个答案:

答案 0 :(得分:2)

可能更容易将数字转换为字符串。创建一个与第一个字符串相反的新字符串。然后进行比较,看看它们是否相同。真的没有理由做任何真正的数学,回文是词汇,而不是数学。

答案 1 :(得分:1)

cin >> num;
num=n;

将用户指定的整数分配给num,然后将其替换为未初始化变量n的值

您的意思是推翻作业吗

n=num;

代替?

  

如果你能帮助我理解我将使用什么样的循环   问一个“你想再试一次吗”

在报告该数字是否为回文后,您可以使用do...while循环,并计算while的条件。

答案 2 :(得分:-2)

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




    }