水仙花数

题目描述:
n为一个三位数n=100x+10y+z
满足条件:x3+y3+z^3=n 称n为水仙花数。
inout: 满足这样条件的三位数
方案一:先获得n的各个位数,再进行验证公式,符合则输出。

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main(){
    vector<int> v2;
    for(int outLoop=100;outLoop<=999;outLoop++){
        int k=0;
        int *v1=new int[10]();
        int inLoop=outLoop;
        while (inLoop!=0)
        {
            v1[k]=inLoop%10;
            inLoop/=10;
            k++;
        }
        int sum1=0;
        for(size_t i=0;i<10;i++){
            sum1+=pow(v1[i],3);
        }
        if(sum1==outLoop){
            v2.push_back(outLoop);
        }
        delete []v1;
    }
    for(auto v22:v2){
        cout<<v22<<' ';
    }
    return 0;
}

方案二:用类实现以上方法。

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
class Flower{
    public:
        ~Flower();
        Flower(int n1):n(n1){ }//有参构造器
        void mPrint(){
            cout<<n<<' ';
        }
        void getWei(){//获得各位数的方法
            int n2=n;
            size_t k=0;
            while(n2){
                v1[k]=n2%10;
                n2/=10;
                k++;
            } 
        }
        bool mIsRight(){//验证条件的函数bool
            getWei();
            bool isRight=false;
            int sum1=0;
            for(size_t i=0;i<3;i++){
                sum1+=pow(v1[i],3);
            }
            if(sum1==n){
                isRight=true;
            }
            return isRight;
        }
    
    private:
        int n;
        int *v1=new int[10];//出现指针时一定要管理内存,建立析构函数将其释放
};
Flower::~Flower(){
    if(v1!=NULL){
        delete []v1;
    }
}
int main(){
    for(int i=100;i<=999;i++){
        Flower f(i);
        if(f.mIsRight()){
            f.mPrint();
        }
    }
    system("pause");
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值