第四周实验报告 任务三

#include <iostream> 

#include <string>

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 的水仙花数; 
}; 

int 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();

	cout << endl; 

	nn.setValue (6);

	cout<< nn.getValue() <<(nn.isPerfect()?"是":"不是")<<"完全数" <<endl;

	nn.setValue (26);   

	cout<<nn.getValue()<<" 和"<<62<<" "<<((nn.isReverse(62))?"是":"不是") << "逆向数" <<endl; 

	nn.setValue (100000);

	cout << "所有大于0,且小于数据成员的水仙花数有:";

	nn.printDaffodils();   

	system ("pause");

	//随着成员函数的实现,增加代码以完成相关的测试。注意判断类的成员函数需要测试是或否两种情况……  
} 
//请在下面定义类中的各个成员函数 

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

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

bool NaturalNumber::isPrime()
{
	for (int i = n / 2; i > 1; --i)
	{
		if (!(n % i))
		{
			return false;
		}
		else 
		{
			return true;
		}
	}
}

void NaturalNumber::printFactor()
{
	cout << n << '\t';

	for (int i = n / 2; i > 0; --i)
	{
		if (!(n % i))
		{
			cout << i << '\t';
		}
	}
}

bool NaturalNumber::isPerfect()
{
	int sum = 0;

	for (int i = n / 2; i > 0; --i)
	{
		if (!(n % i))
		{
			sum += i;
		}
	}
	if (sum == n)
	{
		return true;
	}
	else 
	{
		return false;
	}
}

bool NaturalNumber::isReverse(int x)
{
	int s = 0;

	for (;x != 0;)
	{
		s = s * 10 + x % 10; 

		x = x / 10;
	}
	if (s == n)
	{
		return true;
	}
	else 
	{
		return false;
	}
}

bool NaturalNumber::isDaffodil(int x)
{
	int s = 0, p = x;

	int m;  

	for (;p != 0;)  
	{  
		m = p % 10; 

		s = s + m * m * m; 

		p = p / 10;  
	} 
	if (s == x)
	{
		return true;
	}
	else 
	{
		return false;
	}
}

void NaturalNumber::printDaffodils()
{
	for(int i = 2; i < n; ++i) 
	{
		if(isDaffodil(i)) 
		{
			cout << i <<" ";
		}
	}
	cout << endl; 
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章