项目名称:正整数类
一、问题及代码
- /*
- * 文件名称:Ex5-2.cpp
- * 作 者:程家琦
- * 完成日期:2017 年 4 月 24 日
- * 版 本 号:v1.0
- * 对任务及求解方法的描述部分:设计一个“正整数”类,并通过一系列的成员函数对其性质进行做出判断或列出相关联的数值。下面给出类声明,请实现各成员函数。另外,模仿已经给出的main()函数,完成你所设计的各个成员函数的测试。
- * 输入描述:无
- * 问题描述:我的第一个C++程序,熟悉程序的编辑、运行过程
- * 程序输出:“Hello C++!”
- * 问题分析:略
- * 算法设计:略
- */
- #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 (3);
- cout<<nn.getValue()<<(nn.isPrime()?"是":"不是")<<"素数" <<endl;
- nn.setValue (21);
- cout<<nn.getValue()<<(nn.isPrime()?"是":"不是")<<"素数" <<endl;
- nn.setValue (77);
- cout<<nn.getValue()<<"的因子有:";
- nn.printFactor();
- nn.setValue (3);
- cout<<nn.getValue()<<(nn.isPerfect()?"是":"不是")<<"完数" <<endl;
- nn.setValue (7);
- cout<<nn.getValue()<<(nn.isPerfect()?"是":"不是")<<"完数" <<endl;
- nn.setValue (234);
- cout<<"432"<<(nn.isReverse(123)?"是":"不是")<<nn.getValue()<<"逆向数" <<endl;
- nn.setValue (432);
- cout<<"167"<<(nn.isReverse(167)?"是":"不是")<<nn.getValue()<<"的逆向数" <<endl;
- cout<<"48"<<(nn.isDaffodil(48)?"是":"不是")<<"水仙花数" <<endl;
- cout<<"98"<<(nn.isDaffodil(98)?"是":"不是")<<"水仙花数" <<endl;
- nn.setValue (678);
- nn.printDaffodils();
- //随着成员函数的实现,增加代码以完成相关的测试。注意判断类的成员函数需要测试是或否两种情况……
- }
- //请在下面定义类中的各个成员函数
- void NaturalNumber::setValue (int x)
{
n=x;
if(n>0)
{
cout<<n<<"是正整数。";
}
else
{
cout<<n<<"不是正整数。";
}
return;
}
int NaturalNumber::getValue()
return n;
}
bool NaturalNumber::isPrime()
{
int t=0;
if(n<=1)
return false;
for(int i=2;i<n;++i)
{
t=n%2;
if(t==0)
return false;
}
return true;
}
void NaturalNumber::printFactor()
{
int t;
for(int i=1;i<n;++i)
{
t=n%i;
if(t==0)
cout<<i<<'\t';
}
cout<<endl;
return;
}
bool NaturalNumber::isPerfect()
{
int t,m=0;
for(int i=1;i<n;++i)
{
t=n%i;
if(t==0)
m=m+i;
}
if(m==n)
return true;
return false;
}
bool NaturalNumber::isReverse(int x)
{
int a,b,c;
a=x/100;
b=(x%100)/10;
c=(x%100)%10;
x=c*100+b*10+a;
if(x==n)
return true;
return false;
}
bool NaturalNumber::isDaffodil(int x)
{
int a,b,c,h;
a=x/100;
b=(x%100)/10;
c=(x%100)%10;
h=c*c*c+b*b*b+a*a*a;
if(x==h)
return true;
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;
}
二、运行结果
三、心得体会
采用循环,函数求逆向数与水仙花数
四、知识点总结
对于类的构造。函数的调用与循环