问题理解都在代码注释中说明
问题一:判断回文数字;
代码如下:
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void phuiwen(int);
int main(int argc, char *argv[]) {
//判断回文数字问题:主要是运用取余判断;
//回文数字就是数字逆序输出与原数据比较大小,相等即可证明为回文数字;
//逆序我们可以运用数组存储,然后计算大小与原数进行比较;
int n;
printf("请输入一数字(判断该数字是否为回文数字):");
scanf("%d",&n);
phuiwen(n);
return 0;
}
void phuiwen(int n){
int i=1;
int b=n;
int sum=0;
int s=1;
int a[100];
while(b){
a[i]=b%10;
b/=10;
i++;
}
while(i!=1){
sum+=a[i-1]*s;
s*=10;
i--;
}
if(sum==n){
printf("该数字是回文数字;");
}else{
printf("该数字不是回文数字;");
}
}
运行结果
问题二:寻找水仙花数;
代码如下:
方法一:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void sxhs(int);
int main(int argc, char *argv[]) {
//水仙花数:1,它是一位三位数。
// 2,水仙花数本身等于各位数字的立方和。
//目标:寻找所有的水花仙数;
int i;
printf("输出所有的水仙花数:");
for(i=100;i<1000;i++){
sxhs(i);
}
return 0;
}
void sxhs(int n){
int m=n;
int i;
int sum=0;
while(m){
i=m%10;
sum+=pow(i,3);
m/=10;
}
if(sum==n){
printf("%d ",n);
}else{
return;
}
}
方法二:
代码如下:
#include <stdio.h>
#include <stdlib.h>
int sxhs(int);
int main(int argc, char *argv[]) {
int i;
printf("输出所有的水仙花数:");
for(i=100;i<1000;i++){
if(sxhs(i)){
printf("%d ",i);
}
}
return 0;
}
int sxhs(int n){
int m=n;
int i;
int sum=0;
while(m){
i=m%10;
sum+=i*i*i;
m/=10;
}
if(sum==n){
return 1;
}else{
return 0;
}
}
运行结果: