c++:编一函数int f(int n),功能为判断一个整数n是否为回文数

编一函数int f(int n),功能为判断一个整数n是否为回文数(回文是指正读、倒读都一样的数,如121,2332都是回文数),若是,函数的返回值为1,否则为0。在主函数中统计并输出四位正整数中回文数的个数。

//参考代码如下:
#include <stdio.h>
int f(int n)//判断是否是回文数,是返回1,否则返回0
{
int t=0,m=n;
while(m)//如果m不等于0,执行下面循环,否则跳出循环 ï¼ˆæ±‚这个数各位上数字反向排列的数 ï¼‰ 
{
t*=10;
t+=m%10;
m/=10;
}
return t==n;//如果这个数各位数字反向排列所得数依然等于该数,该数就是回文数 
}
int main(){
int i,n;
for(i=1000,n=0;i<10000;i++)//计算1000-10000直接的回文数,如果是打印出来 
{
if(f(i)){
printf("%d\n",i);
n++;
}
}
printf("count:%d\n",n);//输出总的回文数 
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-01-01
函数如下:
int f(int n)
{
int a[100] = {0};
int top = -1;

while (n > 0) //提取各位数字
{
a[++top] = n % 10;
n /= 10;
}

int left = 0;
while (left < top)//判断是否回文
{
if (a[left++] != a[top--])
return 0;
}
return 1;
}

完整程序如下:
#include <iostream>
using namespace std;

int f(int n)
{
int a[100] = {0};
int top = -1;

while (n > 0) //提取各位数字
{
a[++top] = n % 10;
n /= 10;
}

int left = 0;
while (left < top)//判断是否回文
{
if (a[left++] != a[top--])
return 0;
}
return 1;
}

int main()
{
int i=0,count=0;

cout<<"四位正整数中回文数有: "<<endl;
for(i=1000;i<10000;i++)
if(f(i))
{
cout<<i<<"\t";
count++;
}

cout<<"共有"<<count<<"个。"<<endl;

return 0;
}
第2个回答  2012-01-01
#include <iostream>
using namespace std;
int f(int n){
int m,t,sum=0;
m=n;
while(m>0){
t=m%10;
sum=sum*10+t;
m/=10;
}
return sum==n;
}

main(){
int i,n=0;
for(i=1000;i<9999;i++)
if(f(i)==1){
n++;
cout << i << ' ';
}
cout << endl;
cout << "整数个数 " << n << endl;
}
sorry,调试了一下追问

不对- -

第3个回答  推荐于2017-11-24
#include <stdio.h>
int f(int n)
{
int t=0,m=n;
while(m)
{
t*=10;
t+=m%10;
m/=10;
}
return t==n;
}
int main(){
int i,n;
for(i=1000,n=0;i<10000;i++)
{
if(f(i)){
printf("%d\n",i);
n++;
}
}
printf("count:%d\n",n);
}本回答被提问者采纳
第4个回答  2012-01-01
#include<stdio.h>
#include<string.h>
int f(int n)
{
char a[32];
int i,n;
sprintf(a,"%d",n);
n=strlen(a);
for(i=0,n-=1;i<=n;i++,n--)
{
if(a[i]!=a[n])
return 0;
}
return 1;
}
相似回答