第四周实验报告3(不完全版)

来源:互联网 发布:编程辅助工具 编辑:程序博客网 时间:2024/05/07 23:54

实验目的:设计一个“正整数”类,并通过一系列的成员函数对其性质作出判断或列出相关联的数值

实验代码:

#include <iostream>using namespace std;class NaturalNumber{private:int n;public:void setValue(int x); //置数据成员n的值,要求判断是否是正整数int getValue(); //返回私有数据成员n的值bool isPrime(); //判断数据成员n是否为素数,是返回true,否则返回falsevoid printFactor(); //输出数据成员n的所有因子,包括1和n自身bool isPerfect(); //判断数据成员n是否为完全数bool isReverse(int x); //判断形式参数x是否为数据成员n的逆向数bool isDaffodil(int x); //判断形式参数x是否是水仙花数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();cout << endl;nn.setValue(6);cout << nn.getValue() << (nn.isPerfect()?"是":"不是") << "完全数" << endl;nn.setValue(24);cout << nn.getValue() << (nn.isPerfect()?"是":"不是") << "完全数" << endl;int x;cin >> x;nn.setValue(123);cout << nn.getValue() << (nn.isReverse(x)?"是此数的":"不是此数的") << "逆向数" << endl;int y;cin >> y;nn.setValue(123456);cout << nn.getValue() << (nn.isReverse(y)?"是此数的":"不是此数的") << "逆向数" << endl;int z;cin >> z;    nn.setValue(z);cout << nn.getValue() << (nn.isDaffodil(z)?"是":"不是") << "水仙花数" << endl;}void NaturalNumber::setValue(int x) //置数据成员n的值,要求判断是否是正整数{if(x > 0)n = x;else{cout << "输入的数据不是正整数";exit(0);}}int NaturalNumber::getValue() //返回私有数据成员n的值{return n;}bool NaturalNumber::isPrime() //判断数据成员n是否为素数,是返回true,否则返回false{for(int i = 1, j = 0; i <= n; i++){if(n % i == 0)j++;}if(j > 2)return false;elsereturn true;}void NaturalNumber::printFactor() //输出数据成员n的所有因子,包括1和n自身{for(int i = 1; i <= n; i++){if( n % i == 0){cout << i << " ";}}}bool NaturalNumber::isPerfect() //判断数据成员n是否为完全数{for(int i = 1, m = 0; i < n; i++){if(n % i == 0){m = m + i;}}if(m == n)return true;elsereturn false;}bool NaturalNumber::isReverse(int x) //判断形式参数x是否为数据成员n的逆向数{int a[10];    for(int i = 0; x >= 10; i++){a[i] = x % 10;x = x / 10;}a[i] = x;for(int m = 0, j = 1; i >= 0; i--, j = j * 10){m = m + a[i] * j;}if(m == n)return true;    elsereturn false;}bool NaturalNumber:: isDaffodil(int x) //判断形式参数x是否是水仙花数{int a[10];    for(int i = 0; x >= 10; i++){   a[i] = x % 10;x = x / 10;}a[i] = x;for(int m = 0; i >= 0; i--){m = m + a[i] * a[i] * a[i];}if(m == n)return true;    elsereturn false;}


实验记过截图:

原创粉丝点击