设计一个“正整数”类,并通过一系列的成员函数对其性质进行做出判断或列出相关联的数值。下面给出类声明,请实现各成员函数。另外,模仿已经给出的main()函数,完成你所设计的各个成员函数的测试。
给出的程序段为:
#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的所有因子,包括和n自身
bool isPerfect(); //判断数据成员n是否为完全数。若一个正整数n的所有小于n的因子之和等于n, 则称n为完全数, 如=1+2+3是完全数。
bool isReverse(int x);//判断形式参数x是否为数据成员n的逆向数(例是的逆向数)。
bool isDaffodil(int x); //判断形式参数x是否是水仙花数。水仙花数的各位数字立方和等于该数,如=1*1*1+5*5*5+3*3*3
void printDaffodils(); //显示所有大于,且小于数据成员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();
nn.setValue(6);
cout << nn.getValue() << (nn.isPerfect()?"是":"不是") << "完全数" <<endl;
nn.setValue(123);
cout << nn.getValue() << (nn.isReverse(321)?"是":"不是") << "逆向数" <<endl;
nn.setValue(153);
cout << nn.getValue() << (nn.isDaffodil(153)?"是":"不是") << "水仙花数" <<endl;
nn.setValue(1000);
nn.printDaffodils();
}
void NaturalNumber::setValue (int x)
{
if((x >= 0) && (x - int(x - 1) == 1))
{
cout << x << "是一个正整数,";
}
else
{
cout << x << "不是正整数,";
}
n = x;
}
int NaturalNumber::getValue()
{
return n;
}
bool NaturalNumber::isPrime()
{
for(int i = 2; i <= n - 1; i++)
{
if (n % i == 0)
{
return true;
}
else
{
return false;
}
}
}
void NaturalNumber::printFactor()
{
for(int i = 1; i <= n; i++)
{
if(n % i == 0)
{
cout << i << ' ' ;
}
}
cout <<endl;
}
bool NaturalNumber::isPerfect()
{
int i, t;
int sum = 0;
for(i = 1; i <= n - 1; i++)
{
if(n % i ==0)
{
t = i;
sum = sum + t;
}
if(n == sum)
{
return true;
}
else
{
return false;
}
}
}
bool NaturalNumber::isReverse(int x)
{
if((n % 10 == x /100) && ((n /10)%10 == (x / 10)%10) && (n / 100 == x %10))
{
return true;
}
else
{
return false;
}
}
bool NaturalNumber::isDaffodil(int x)
{
int i, j, k;
i = x /100;
j = (x / 10)%10;
k = x %10;
if(x == i* i* i+ j* j* j+ k* k* k)
{
return true;
}
else
{
return false;
}
}
void NaturalNumber::printDaffodils()
{
int i, j, k;
cout << "所有大于,且小于数据成员" << n << "的水仙花数:" <<endl;
if(n < 100)
{
cout << "无水仙花数!" <<endl;;
}
else
{
for(int m = 100; m < n; m++)
{
i = m /100;
j = (m / 10)%10;
k = m %10;
if(m == i* i* i+ j* j* j+ k* k* k)
{
cout << m << ' ';
}
}
}
cout <<endl;
}
输出结果: