c++第五次实验-正整数类

来源:互联网 发布:mac专用dj软件 编辑:程序博客网 时间:2024/06/14 09:46
一、问题及代码/*  * 文件名称:正整数类.cpp  * 作    者:潘维涵  * 完成日期:2017 年 4 月 24 日  * 版 本 号:v1.0  * 对任务及求解方法的描述部分: * 输入描述:输入x  * 问题描述:正整数类* 程序输出:判断正整数类* 问题分析:略 * 算法设计:略  */    #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,否则返回false  void printFactor(int x);  //输出数据成员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){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(84);int x;cout << endl << "请输入一个整数:";cin >> x;nn.isReverse(x);cout << nn.getValue() << (nn.isReverse(x) ? "是" : "不是") << x << "的逆向数" << endl;nn.isDaffodil(x);cout << nn.getValue() << (nn.isDaffodil(x) ? "是" : "不是") << "水仙数" << endl;cout << "比" << x << "小的水仙花数有:" << endl;nn.printDaffodils();//随着成员函数的实现,增加代码以完成相关的测试。注意判断类的成员函数需要测试是或否两种情况……      }//请在下面定义类中的各个成员函数  void NaturalNumber::setValue(int x){n = x;if (x>0){cout << n << "是正整数" << endl;}}int NaturalNumber::getValue(){return n;}bool NaturalNumber::isPrime(){int count = 0;for (int i = 2; i<n; i++){if (n%i != 0){count++;}}if (count == n - 2){return true;}else{return false;}}bool NaturalNumber::isPerfect(){int sum = 0;for (int i = 2; i <= n; i++){if (n%i == 0){sum += i;}}if (sum == n){cout << n << "是完全数" << endl;return true;}else{cout << n << "不是完全数" << endl;return false;}}void NaturalNumber::printFactor(int x){for (int i = 1; i <= x; i++){if (x%i == 0){cout << i << ' ';}}}bool NaturalNumber::isReverse(int x){int a, b, c, m, p, t;a = x / 100;b = x / 10 % 10;c = x % 10;m = n / 100;p = n / 10 % 10;t = n % 10;if ((a == t)&&(b == p)&&(c == m)){return true;}else if(b==t&&p==c&&a==0&&m==0){return true;}else if (a == b == m == p == 0 && c == t){return true;}else{return false;}}bool NaturalNumber::isDaffodil(int x){int a, b, c;a = x / 100;b = x / 10 % 10;c = x % 10;if (x == pow(a, 3) + pow(b, 3) + pow(c, 3)){return true;}else{return false;}}void NaturalNumber::printDaffodils(){int a, b, c;for (int i = 1; i < n; i++){a = i / 100;b = i / 10 % 10;c = i % 10;if (n== pow(a, 3) + pow(b, 3) + pow(c, 3)){cout << i << ' ';}}}
二、运行结果:
三、心得体会:
类相当难,可得好好学习
四、知识点总结:
使用public之中的函数来对私有数据进行操作

0 0