01.#include<iostream>
02.
03.using namespace std;
04.
05.class NaturalNumber
06.{
07.private:
08. int n;
09.public:
10. void setValue (int x);//置数据成员n的值,要求判断是否是正整
11. int getValue(); //返回私有数据成员n的值
12. bool isPrime(); //判断数据成员n是否为素数,是返回true,否则返回false
13. void printFactor(); //输出数据成员n的所有因子,包括和n自身
14. bool isPerfect(); //判断数据成员n是否为完全数。若一个正整数n的所有小于n的因子之和等于n, 则称n为完全数, 如=1+2+3是完全数。
15. // bool isReverse(int x);//判断形式参数x是否为数据成员n的逆向数(例是的逆向数)。
16. bool isDaffodil(int x); //判断形式参数x是否是水仙花数。水仙花数的各位数字立方和等于该数,如=1*1*1+5*5*5+3*3*3
17. void printDaffodils(); //显示所有大于,且小于数据成员n的水仙花数;
18.};
19.
20.void main(void)
21.{
22. NaturalNumber nn; //定义类的一个实例(对象)
23. nn.setValue (6);
24. cout<<nn.getValue()<<(nn.isPrime()?"是":"不是")<<"素数" <<endl;
25.
26. nn.setValue (37);
27. cout<<nn.getValue()<<(nn.isPrime()?"是":"不是")<<"素数" <<endl;
28.
29. nn.setValue (84);
30. cout<<nn.getValue()<<"的因子有:";
31. nn.printFactor();
32.
33. nn.setValue(6);
34. cout << nn.getValue() <<(nn.isPerfect()?"是":"不是") << "完全数" << endl;
35.
36. nn.setValue(352);
37. cout << nn.getValue() <<(nn.isPerfect()?"是":"不是") << "完全数" << endl;
38.
39. nn.setValue (968);
40. cout<<"所有大于,且小于数据成员"<<nn.getValue()<<" 的水仙花数有:";
41. nn.printDaffodils();
42.
43. system("PAUSE");
44.}
45.
46.
47.//请在下面定义类中的各个成员函数
48.////置数据成员n的值,要求判断是否是正整数
49.void NaturalNumber::setValue (int x)
50.{
51. n=x;
52.}
53.
54.//返回私有数据成员n的值
55.int NaturalNumber::getValue()
56.{
57. return n;
58.}
59.
60.//判断数据成员n是否为素数,是返回true,否则返回false
61.bool NaturalNumber::isPrime()
62.{
63. int i;
64.
65. for(i=2;i<=n/2;i++)
66. {
67. if(n%i==0)
68. {
69. return false;
70. break ;
71. }
72. else
73. return true;
74. }
75.}
76.
77.//输出数据成员n的所有因子,包括和n自身
78.void NaturalNumber::printFactor()
79.{
80. for(int i=1;i<=n;i++)
81. {
82. if(n%i == 0)
83. cout << i << " ";
84.
85. }
86. cout << endl;
87. return ;
88.}
89.//判断形式参数x是否是水仙花数
90.bool NaturalNumber::isPerfect()
91.{
92. int i,s=0,t=0;
93. for(i=1;i<=(n/2);i++)
94. {
95. if(n%i == 0)
96. {
97. s = s+i;
98. }
99. }
100. if(s==n)
101. return true;
102. else
103. return false;
104.}
105.
106.//判断数据成员n是否为完全数。
107.bool NaturalNumber::isDaffodil(int x)
108.{
109. int t=0,m,a;
110. m=x;
111. while(m>0)
112. {
113. a=m%10;
114. t=t+a*a*a;
115. m=m/10;
116. }
117. if(t == x)
118. return true;
119. else
120. return false;
121.}
122.
123.//显示所有大于,且小于数据成员n的水仙花数
124.void NaturalNumber::printDaffodils()
125.{
126. int i;
127. for(i=1;i<n;i++)
128. {
129. if(isDaffodil(i))
130. cout << i << " ";
131. }
132. cout << endl;
133.
134.}