#include<iostream>
using namespace std;
class NaturalNumber
{
private:
int n;
public:
void setValue (int x);//置数据成员n 的值,要求判断是否是正整数
int getValue(); //返回私有数据成员n 的值
bool isPrime(); //判断数据成员n 是否为素数,是返回true,否则返回false
void printFactor(); //输出数据成员n 的所有因子,包括1 和n 自身
bool isPerfect(); //判断数据成员n 是否为完全数。若一个正整数n 的所有小于n 的因子之和等于
//n, 则称n 为完全数, 如6=1+2+3 是完全数。
bool isReverse(int x);//判断形式参数x 是否为数据成员n 的逆向数(例321 是123 的逆向数)。
bool isDaffodil(int x); //判断形式参数x 是否是水仙花数。水仙花数的各位数字立方和等于该数,
//如153=1*1*1+5*5*5+3*3*3
void printDaffodils(); //显示所有大于1,且小于数据成员n 的水仙花数;
};
void main(void)
{
NaturalNumber nn; //定义类的一个实例(对象)
nn.setValue (6);
cout<<nn.getValue()<<(nn.isPrime()?"是":"不是")<<"素数" <<endl;
nn.setValue (37);
cout<<nn.getValue()<<(nn.isPrime()?"是":"不是")<<"素数" <<endl;
nn.setValue (84);
cout<<nn.getValue()<<"的因子有:";
nn.printFactor();
cout << endl;
nn.setValue(6);
cout<<nn.getValue()<<(nn.isPerfect()?"是":"不是")<<"完全数" <<endl;
nn.setValue(123);
cout << nn.getValue() <<(nn.isReverse(123)?"是":"不是") <<"逆向数"<<endl;
nn.setValue(153);
nn.isDaffodil(153);
cout << nn.getValue() << (nn.isDaffodil(153)?"是":"不是")<< "水仙花数"<< endl;
nn.setValue(888);
cout << "1到" <<nn.getValue()<<"水仙花数有:";
nn.printDaffodils();
//随着成员函数的实现,增加代码以完成相关的测试。注意判断类的成员函数需要测试是或否
//两种情况……
}
//请在下面定义类中的各个成员函数
void NaturalNumber::setValue(int x)
{
n = x;
}
int NaturalNumber::getValue()
{
return n;
}
bool NaturalNumber::isPrime()
{
int x,y,z=0;
for(x=2;x<(n/2);x++)
{
y = n%x;
if(y!=0)
z++;
}
if(z!=0)
return true;
else
return false;
}
void NaturalNumber::printFactor()
{
int j = 0;
for(int i = 1;i <= (n/2); i++)
{
j = n%i;
if(j == 0)
{
cout << i <<",";
}
else
continue;
}
}
bool NaturalNumber::isPerfect()
{
int m = 0;
for(int i = 1; i < n; i++)
{
if(n%i == 0)
{
m = m + i ;
}
else
continue;
}
if(m = n)
{
return true;
}
else
return false;
}
bool NaturalNumber::isReverse(int x)
{
int a = 0;
while(x > 0)
{
a = a*10 + x%10;
x = x / 10;
}
if(n == a)
return true ;
else
return false;
}
bool NaturalNumber::isDaffodil(int x)
{
int p = 0,s = 0;
while(x > 0)
{
p = x%10;
s = s + p*p*p;
x = x/10;
}
if(n == s)
return true;
else
return false;
}
void NaturalNumber::printDaffodils()
{
int a,b,c,h;
cout<<endl;
cout<<"所有大于1,且小于数据成员"<<n<<"的水仙花数为:";
for(int i=11;i<n;++i)
{
if(i<100)
{
a=i/10;
b=i%10;
h=a*a*a+b*b*b;
if(i==h)
cout<<i<<'\t';
}
else
{
a=i/100;
b=(i%100)/10;
c=(i%100)%10;
h=c*c*c+b*b*b+a*a*a;
if(i==h)
cout<<i<<'\t';
}
}
cout<<endl;
}
总结:秋水仙花数也要考虑效率问题