源程序:
#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 print_Daffodils(); //显示所有大于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();
nn.setValue (84);
cout<< (nn.isReverse(48)?"x是":"x不是") << nn.getValue() << "的逆向数" <<endl;
nn.isDaffodil(153);
cout<< (nn.isDaffodil(153)?"x是":"x不是") << "水仙花数" <<endl;
nn.setValue (1000);
cout<<"所有大于1,且小于数据成员"<<nn.getValue()<<" 的水仙花数有:";
nn.print_Daffodils();
system("PAUSE");
//随着成员函数的实现,增加代码以完成相关的测试。注意判断类的成员函数需要测试是或否两种情况……
}
//请在下面定义类中的各个成员函数
void NaturalNumber::setValue (int x)
{
n = x;
while(1)
{
if(x < 0)
{
cout<< "请输入正整数!!!";
break;
}
else
{
break;
}
}
}
int NaturalNumber::getValue()
{
return n;
}
bool NaturalNumber::isPrime()
{
if(n % 2 == 0 || n % 3 == 0)
{
return false;
}
else
{
return true;
}
}
void NaturalNumber::printFactor()
{
int i;
for(i = 1; i <= n; ++ i)
{
if(n % i == 0)
{
cout<< i << " ";
}
else
{
continue;
}
}
cout<< endl;
}
bool NaturalNumber::isPerfect()
{
int i, sum = 0;
for(i = 1; i < n; ++i)
{
if(n % i == 0)
{
sum = sum + (n % i);
}
else
{
continue;
}
}
if(sum == n)
{
return true;
}
else
{
return false;
}
}
bool NaturalNumber::isReverse(int x)
{
int s = 0, a = 0;
while(x > 0)
{
a = x % 10;
s = s * 10 + a;
x = x / 10;
}
if(s == n)
{
return true;
}
else
{
return false;
}
}
bool NaturalNumber::isDaffodil(int x)
{
int a = 0, s = 0;
int y = x;
while(y > 0)
{
a = y % 10;
s = s + a * a * a;
y = y / 10;
}
if(s == x)
{
return true;
}
else
{
return false;
}
}
void NaturalNumber::print_Daffodils()
{
for(int i = 2; i < n; ++ i)
{
if(isDaffodil(i))
{
cout<< i <<" ";
}
}
cout<< endl;
}
截图:
收获:复习了以前的快要忘记了的知识~有些地方还是不太熟悉....至于那个xx是xx的逆向数那个地方····实在不知道该如何输出···
感想:越做越顺利呢!