输出100—999中所有的水仙花数,若3位数xyz满足
, 则xyz为水仙花数,例如
, 因此153是水仙花数。
#include <iostream>
using namespace std;
// 方法一
void daffodil_1()
{
int a = 0;
for (int x=1; x<10; x++)
{
for (int y =0; y<10; y++)
{
for (int z = 0; z<10; z++)
{
a = 100*x+10*y+z;
if (a== x*x*x + y*y*y + z*z*z)
{
cout<<a<<" 是水仙花数"<<endl;
}
}
}
}
}
// 方法二
void daffodil_2()
{
int x = 0;
int y = 0;
int z = 0;
for (int n=100; n<1000; n++)
{
x = n / 100;
y = (n % 100)/10 ;
z = n % 10;
if(n == x*x*x + y*y*y +z*z*z)
{
cout<<n<<" 是水仙花数"<<endl;
}
}
}
int main()
{
cout<<"----------daffodil_1()---------"<<endl;
daffodil_1();
cout<<endl;
cout<<"----------daffodil_2()---------"<<endl;
daffodil_2();
return 0;
}