请哪位高手给我解释一下下面这段C语言求回文的意思。。最好详细一点。。。谢谢~

#include<stdio.h>
#include<conio.h>
void main()
{
int num,rev=0,temp,res;
clrscr();
printf("\n\nLab : 4 Program that reverse the given number and check it for Palindrome.");
printf("\n***************************************************************************");
printf("\n\n\n\tPlease enter a number : ");
scanf("%d",&num);
temp=num;
while(temp!=0)
{
res=temp%10;
rev=rev*10+res;
temp=temp/10;
};
if(num==rev)
{
printf("\n\n\t\tGiven number %d is a Palindrome",num);
}
else
{
printf("\n\n\t\tGiven number %d is not a Palindrome",num);
};
getch();
}
我就是弄不懂while(temp!=0)
{
res=temp%10;
rev=rev*10+res;
temp=temp/10;

这是什么意思。。。有谁能解释下。。。谢了~

其实这个循环的整个过程就是将num的数值倒序过来,如123,倒序后就是321,。回文数有个特点正序和倒序,数值都是相等的,其他数就不会有这种特点。可以拿个数值试试。
num = 121
第一次循环:res = 1;rev = 0 * 10 + 1 = 1; temp = 12;
第二次循环:res = 2, rev = 1*10 + 2 = 12; temp =1;
第三次循环:res = 1, rev= 12 * 10 + 1 = 121; temp = 0;
循环结束后:rev == num,是回文数
num = 123
第一次循环:res = 3;rev = 0 * 10 + 3 = 3; temp = 12;
第二次循环:res = 2, rev = 3*10 + 2 = 32; temp =1;
第三次循环:res = 1, rev= 32* 10 + 1 = 321; temp = 0;
循环结束后:rev != num,不是回文数。
还有一种方式:分解出num所有位的数值,然后将最高位和最低位比较是否相等,如不相等,则说明不是回文数,如相等再比较次高位和次低位是否相等,依次这样比较下去。
temp = num;
int a[10];这里设置10个元素,原因是int类型的最大数值为4294967296,总共十位
int i = 0;
int result = num;
while(result!= 0)
{
a[i] = result %10; //余数就是num的第i位数值
result = result /10;
i++;
}
a[i] = result; // 存储最高位
bool bResult = true; //初始认为该数为回文数
for(int j =0; j <=i; j++,i--)
{
if(a[j] != a[i])
{
bResult = false;//对称为不相等说明不是回文数
break;
}
}
if(bResult == true)
{
printf("\n\n\t\tGiven number %d is a Palindrome",num);
}
else
{
printf("\n\n\t\tGiven number %d is not a Palindrome",num);
}
算法很简单,拿个数值,按着代码一点点算就明白是什么意思了。
温馨提示:内容为网友见解,仅供参考
第1个回答  2011-09-03
scanf输入一个int类型数,赋值给了temp变量
while(temp!=0) //如果temp不等于0就执行下面的
{
res=temp%10; //temp/10的余数给了res
rev=rev*10+res; //rev=0*10+res
temp=temp/10; //temp/10的结果再赋值给temp
};追问

temp为什么要除以10?
还有res是什么啊?

第2个回答  2011-09-03
你要是懂了回文的意思就知道为什么除以10了
相似回答