求水仙花数c语言代码怎么写

求水仙花数c语言代码怎么写,第1张

求水仙花数c语言代码怎么写

求水仙花数c语言代码怎么写

水仙花数(Narcissistic number)也被称为超完全数字不变数(pluperfect digital invariant, PPDI)、自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number),水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身(例如:1^3 + 5^3+ 3^3 = 153)。

推荐学习:c语言视频教程

下面是使用C语言求水仙花数的代码:

#include <stdio.h> 
#include <stdlib.h>
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<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
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中文网!

以上就是求水仙花数c语言代码怎么写的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/686065.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-20
下一篇 2022-04-20

发表评论

登录后才能评论

评论列表(0条)

保存