求水仙花数c语言代码怎么写
水仙花数(Narcissistic number)也被称为超完全数字不变数(pluperfect digital invariant, PPDI)、自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number),水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身(例如:1^3 + 5^3+ 3^3 = 153)。
下面是使用C语言求水仙花数的代码:#include
#include
void main()
{
int i,j,k,n;
printf("'water flower'number is:");
for(n=100;n<1000;n++)
{
i=n/100;/*分解出百位*/
j=n/10%10;/*分解出十位*/
k=n%10;/*分解出个位*/
if(n==i*i*i+j*j*j+k*k*k)
{
printf("%-5d",n);
}
}
printf("\n");
}
升级版:#include
#include
#include
int cube(const int n){
return n*n*n;
}
bool
isNarcissistic(const int n){
int hundreds=n/100;
int tens=n/10-hundreds*10;
int ones=n%10;
return cube(hundreds)+cube(tens)+cube(ones)==n;
}
int main(void){
int i;
for(i=100;i<1000;++i){
if(isNarcissistic(i))
printf("%d\n",i);
}
return EXIT_SUCCESS;
}
更多C语言教程,请关注PHP中文网!