第四周实验报告3

 
#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 printDaffodils(); //显示所有大于1,且小于数据成员n 的水仙花数;
};
void main(void)
{
int x,b,a;
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<<"输入n的值(最多为三位数):";
cin>>x;
nn.setValue (x);
cout<<"请输入一个数:";
cin>>a;
cout<<a<<(nn.isReverse(a)?"是":"不是")<<nn.getValue ()<<"的逆向数"<<endl;
cout<<"输入一个数(最多为三位数):";
cin>>b;
cout<<b<<(nn.isDaffodil(b)?"是":"不是")<<"水仙花数"<<endl;

cout<<"小于n的水仙花数有:";
nn.printDaffodils();

}
void NaturalNumber::setValue (int x)
{
	int m=1;
	while(m)
	{
		if(x>=0)
		{
			m=0;
			n=x;
		}
	}


}
int NaturalNumber::getValue ()
{
	return n;
}

bool NaturalNumber::isPrime()
{
	bool t=true;
	int i;
	for(i=2;i<n;i++)
	{
	
		if(n%i==0)
		{
			t=false;
			break;
		}
	}
	return t;
}

void NaturalNumber::printFactor()
{
	int i;
	for(i=1;i<= n;i++)
	{
		if(n%i==0)
		{
			cout<<i<<" ";
		}
	}
	cout<<endl;
}

bool NaturalNumber::isPerfect()
{
	bool t=true;
	int i,m=0;
	for(i=2;i<n;i++)
	{
		
		if(n%i==0)
		{
			m=m+i;
		}
	}
	if(m!=n)
	{
		t=false;
	}
	return t;
}
bool NaturalNumber::isReverse(int x)
{
	bool t=true;
	int a,b,c;
	    c=x%10;

	    x=x/10;
		b=x%10;
		a=x/10;


	if(n!=(c*100+b*10+a))
	{
		t=false;
	}
	return t;
}
bool NaturalNumber::isDaffodil(int x)
{
	bool t=true;
	int a,b,c,m;
		c=x%10;
	    m=x/10;
		b=m%10;
		a=m/10;
		if(x!=(a*a*a+b*b*b+c*c*c))
	{
		t=false;
	}
	return t;
}
void NaturalNumber::printDaffodils()
{
	int i,a,b,c,m;
	for(i=2;i<=n;i++)
	{
	    c=i%10;
	    m=i/10;
		b=m%10;
		a=m/10;
		if(i==(a*a*a+b*b*b+c*c*c))
		{
			cout<<i<<" ";
		}
	}
	cout<<endl;
}






评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值