第四周项目4

来源:互联网 发布:开票软件000013 编辑:程序博客网 时间:2024/05/22 07:46
#include<iostream>#include<cmath>using namespace std;class NaturalNumber{private:int n; public:void setValue (int x);//置数据成员n的值,要求判断是否是正整数int getValue();  //返回私有数据成员n的值bool isPrime();  //判断数据成员n是否为素数,是返回true,否则返回falsevoid 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*3void printDaffodils(); //显示所有大于1,且小于数据成员n的水仙花数;};void main(void){NaturalNumber nn;//定义类的一个实例(对象)nn.setValue (12);cout<<nn.getValue()<<(nn.isPrime()?"是":"不是")<<"素数" <<endl;cout<<nn.getValue()<<(nn.isPerfect()?"是":"不是")<<"完全数" <<endl;     nn.setValue (21);cout<<nn.getValue()<<(nn.isReverse(12)?"是":"不是")<<"逆向数" <<endl;nn.setValue (12);cout<<nn.getValue()<<(nn.isDaffodil(12)?"是":"不是")<<"水仙花数" <<endl;cout<<"小于"<<nn.getValue()<<"水仙花数有";nn.printDaffodils();cout<<endl;nn.setValue (37); cout<<nn.getValue()<<(nn.isPrime()?"是":"不是")<<"素数" <<endl;cout<<nn.getValue()<<(nn.isPerfect()?"是":"不是")<<"完全数" <<endl; nn.setValue (73);cout<<nn.getValue()<<(nn.isReverse(37)?"是":"不是")<<"它的逆向数" <<endl;    nn.setValue (37);cout<<nn.getValue()<<(nn.isDaffodil(37)?"是":"不是")<<"水仙花数" <<endl;nn.setValue (153);cout<<"小于"<<nn.getValue()<<"水仙花数有";nn.printDaffodils();cout<<endl;nn.setValue (84); cout<<nn.getValue()<<"的因子有:";nn.printFactor();cout<<endl;system("PAUSE");//随着成员函数的实现,增加代码以完成相关的测试。注意判断类的成员函数需要测试是或否两种情况……}//请在下面定义类中的各个成员函数void  NaturalNumber::setValue(int x){if(x>0)n=x;}//置数据成员n的值,要求判断是否是正整数int NaturalNumber::getValue(){return n;}  //返回私有数据成员n的值bool NaturalNumber::isPrime(){if(n==2 || (n%2!=0 && n!=1))return true;elsereturn false;}  //判断数据成员n是否为素数,是返回true,否则返回falsevoid  NaturalNumber:: printFactor(){int i;for(i=1;i<=n;i++){if(n%i==0)cout<<i<<" ";}}  //输出数据成员n的所有因子,包括1和n自身bool NaturalNumber::isPerfect(){int s[100],i,m=0,sum=0;for(i=1;i<=n;i++){if(n%i==0){s[i]=i;m++;}}for(i=1;i<=m;i++){sum=sum+s[i];}if(sum==n)return true;elsereturn false;} //判断数据成员n是否为完全数。若一个正整数n的所有小于n的因子之和等于n, 则称n为完全数, 如6=1+2+3是完全数。bool NaturalNumber::isReverse(int x){  if(((x%10)*10+(x/10)%10)==n)  return true;  else  return false;}//判断形式参数x是否为数据成员n的逆向数(例321是123的逆向数)。bool NaturalNumber::isDaffodil(int x){int a,b,c;   a=x%10;   b=x/10;   c=pow(b,3)+pow(a,3);   if(c==n)   return true;   else   return false;} //判断形式参数x是否是水仙花数。水仙花数的各位数字立方和等于该数,如153=1*1*1+5*5*5+3*3*3void NaturalNumber::printDaffodils(){int a,b,c,d,i;for(i=1;i<=n;i++){   a=i%10;   b=(i%100)/10;   d=i/100;   c=pow(b,3)+pow(a,3)+pow(d,3);   if(c==n)   cout<<i<<" ";}}


运行结果:

原创粉丝点击