题目十三
打印出所有的“水仙花数,所谓的水仙花数是指一个三位数,其各位数字立方和等于该数的平方
代码如下:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[3];
for(int i=100;i<1000;i++)
{
a[0]=i%10; //个位数字
a[1]=(i%100)/10;//十位数字
a[2]=i/100; //百位数字
if(i==a[0]*a[0]*a[0]+a[1]*a[1]*a[1]+a[2]*a[2]*a[2])
{
printf("水仙花是%d\n",i);
}
}
}
,输出结果图下
记得这块其实可以考虑多位数字的水仙花情况,也可以动态输入范围,判断该范围内的水仙花,但是有点晚了,下篇文章再写吧。
呃呃呃,小助手说我短,那我也没办法了,就这篇文章写了吧。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n;
printf("please input the 位数");
scanf("%d",&n);//输入要求的位数,输出该位数的水仙花。
int s=1;
for (int i=1;i<n;i++)
{
s=s*10;
}
int e=s;
for (e>0;s<=e*10-1;s++)
{
int b;
int a=0;
int c=s;
do
{
b=c%10;
c/=10;
int f=1;
for(int count=0;count <n;count++)
{
f*=b;
}
a+=f;
}while (c>0);
if(s==a)
{
printf("%d\n",a);
}
}
}
代码有点麻烦,欢迎提出改进意见。