要求:定义一个判断回文数的函数,并打印出1000-2000之间所有的回文数。(回文数是指其各位数字左右对称的整数,如1221是回文数)
C++实现:
#include <iostream>
using namespace std;
int judge(int x)
{
int a,b,c,d;
a = x / 1000;
b = x / 100 % 10;
c = x / 10 % 10;
d = x % 10;
if(a == d && b == c)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
cout<<"1000-2000间的回文数有:"<<"\n";
for (int i = 1000; i < 2000; i++) {
if(judge(i)==1)
{
cout<<i<<" ";
}
}
return 0;
}
C语言实现:
#include<stdio.h>
int judge(int x)
{
int a,b,c,d;
a = x / 1000;
b = x / 100 % 10;
c = x / 10 % 10;
d = x % 10;
if(a == d && b == c)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
printf("1000-2000间的回文数有:\n");
for (int i = 1000; i < 2000; i++) {
if(judge(i)==1)
{
printf("%d ",i);
}
}
return 0;
}
Java实现:
public class c_work2 {
public static int yjudge(int x)
{
int a,b,c,d;
a = x / 1000;
b = x / 100 % 10;
c = x / 10 % 10;
d = x % 10;
if(a == d && b == c)
{
return 1;
}
else
{
return 0;
}
}
public static void main(String[] args) {
System.out.println("1000-2000之间的回文数:");
for (int i = 1000; i <= 2000; i++){
if(yjudge(i)==1)
{
System.out.print(i+" ");;
}
}
}
}
运行结果: