用C语言实现水仙花数的判断

C语言方法:

方法一:

#include <stdio.h>
int  main( )
{ int n,a,b,c;
scanf(“%d”,&n); 
a=n%10;
b=n/10%10;
c=n/100;
if(n==a*a*a+b*b*b+c*c*c)
printf(“%d是水仙花数\n”, n); 
else printf(“%d不是水仙花数\n”, n); 
return 0;
}
#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 0;
}

方法三:

#include <stdio.h> 
#include <stdlib.h>
int 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");
    return 0;
} 

C++方法:

方法一:

#include<iostream>
using std::cout;
using std::endl;
#define f(a) (a)*(a)*(a)
int main() {
    for (int i = 100;i < 1000;i++)
        if (f(i % 10) + f(i / 10 % 10) + f(i / 100 % 10) == i)
            cout << i << endl;
    system("pause");
    return 0;
}

方法二:

#include<iostream>
#include<cmath>
using namespace std;
int main(])
{
    long n1, n2, a;
    int i;
    cout << "请输入Narcissistic number的位数:" << endl;
    cin >> i;
    cout << i << "位数的Narcissistic number包括:" << endl;
    for (n1 = pow(10, i - 1); n1 < pow(10, i); n1++)
    {
        n2 = 0;
        for (int j=0; j < i; j++)
        {
            a = pow(10, j);
            a = n1 / a;
            a = a % 10;
            a = pow(a, i);
            n2 = n2 + a;
        }
        if (n1 == n2)
            cout << n1 << endl;
    }
    return 0;
}

  • 13
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惑星撞地球

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值