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.}