一、代码
/*
*文件名称: 了
*作 者: 袁明杰
*完成日期: 2015 年 3 月 27 日
*版 本 号:v1.0
*对任务及求解方法的描述部分:正整数类
*输入描述:略
*问题描述:并通过一系列的成员函数对其性质进行做出判断或列出相关联的数值
*程序输出: 略
*问题分析: 模仿已经给出的main()函数,完成你所设计的各个成员函数的测试。
*算法设计:下面给出类声明,请实现各成员函数。
*/
#include<iostream>
using namespace std;
class NaturalNumber
{
private:
int n;
public:
void setValue (int x)
{
n=x;
if(x>0&&x==(int)x)
cout<<x<<"是正整数"<<endl;
}
int getValue()
{
return n;
}
bool isPrime()
{
int a;
for(a=2;a<=n;a++)
{
if(n%a==0)
break;
}
if(n==a)
return true;
else
return false;
}
void printFactor()
{
int a;
for(a=1;a<=n;a++)
{
if(n%a==0)
cout<<a<<" ";
}
}
bool isPerfect()
{
int a,sum=0;
for(a=1;a<n;a++)
{
if(n%a==0)
sum=sum+a;
}
if(sum==n)
return true;
else
return false;
}
bool isReverse(int x);
bool isDaffodil(int x)
{
if(x==1)
return true;
else if(x<10)
return false;
else if(x<100)
{int a,b;
a=x/10;b=x-a*10;
if((a*a*a+b*b*b)==x)
return true;
else
return false;
}
else if(x<1000)
{
int a,b,c;
a=x/100;b=(x-a*100)/10;c=x-a*100-b*10;
if(x==(a*a*a+b*b*b+c*c*c))
return true;
else
return false;
}
}
void printDaffodils()
{
int x;
for(x=2;x<n;x++)
{
if(x<100&&x>10)
{int a,b;
a=x/10;b=x-a*10;
if((a*a*a+b*b*b)==x)
cout<<x<<" ";
}
else if(x<1000&&x>100)
{
int a,b,c;
a=x/100;b=(x-a*100)/10;c=x-a*100-b*10;
if(x==(a*a*a+b*b*b+c*c*c))
cout<<x<<" ";
}
}
}
};
void main()
{
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(888);
cout<<nn.getValue()<<"的水仙花数有: ";
nn.printDaffodils();
cout<<endl;
}
二、运行结果
三、心得体会
1.在编写这个程序时,有两种方法,既可以在类里声明,类外定义,也可以直接在类里面定义。
2.在编写程序时一定要记住用英文半角。
3.在类里面定义的时候不能加分号。