题目描述:
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;
}