报告:3
实验目的:
实验内容:设计一个“正整数”类,并通过一系列的成员函数对其性质进行做出判断或列出相关联的数值。
下面给出类声明,请实现各成员函数。另外,模仿已经给出的main()函数,完成你所设计的各个成员函数的
测试。
/*
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:
* 作 者:张传新
* 完成日期:2012 年 3 月 15日
* 版 本 号:1
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:
* 程序输出:
* 问题分析:……
* 算法设计:……
*/
#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();//输出数据成员n的所有因子,包括1和n自身
bool isPerfect();//判断数据成员n是否为完全数。若一个正整数n的所有小于n的因子之和
//等于n,则n为完全数,如6=1+2+3是完全数。
bool isReverse(int x);//判断形式参数x是否为数据成员n的逆向数
bool isDaffodil(int x);//判断形式参数x是否为水仙花数
void printDaffodils();//显示所有大于一小于数据成员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() << "的因子有:"<<endl;
nn.printFactor();
//随着成员函数的实现,增加代码以完成相关的测试。注意判断类的成员函数需要测试是或否两种情况……
nn.setValue (6);
cout << nn.getValue() << (nn.isPerfect()?"是":"不是") << "完全数" << endl;
nn.setValue(123);
cout << nn.getValue() << (nn.isReverse(321)?"是":"不是") << "321的逆向数" << endl;
nn.setValue(153);
cout << nn.getValue() << (nn.isDaffodil(153)?"是":"不是") << "水仙花数" << endl;
nn.setValue(999);
cout << "从1到" << nn.getValue() << "的水仙花数是:" << endl;
nn.printDaffodils();
cout << endl;
}
void NaturalNumber::setValue(int x)
{
if(x>0)
{
n=x;
}
}
int NaturalNumber::getValue()
{
return n;
}
bool NaturalNumber::isPrime()
{
for(int i=2;i<=sqrt(n);i++)
{
if(n%i==0)
return false;
}
return true;
}
void NaturalNumber::printFactor()
{
for(int i=1;i<=n;i++)
{
if(n%i==0)
{
cout<<i<<' ';
}
}
cout<<endl;
}
bool NaturalNumber::isPerfect()
{
int s=0;
for(int i= 2;i<n;i++)
{
if(n%i==0)
{
s=s+i;
}
}
if(s==n)
return false;
return true;
}
bool NaturalNumber::isReverse(int x)
{
int w[10],i=0,s;
while(x!=0)
{
w[i++]=x%10;
x=x/10;
}
for(int j=0;j<=i;j++)
{
s=s*10+w[j];
}
if(s==n)
return false;
return true;
}
bool NaturalNumber::isDaffodil(int x)
{
int s=0,y[10],i=0;
while(x!=0)
{
y[i]=x%10;
x=x/10;
}
for(int j=0;j<=i;j++)
{
s=s+y[j]*y[j]*y[j];
}
if(s==n)
return false;
return true;
}
void NaturalNumber::printDaffodils()
{
int a[10], i, s=0, x;
for (int num=2; num<=n;num++)
{
i=0, s=0;
x=num;
do{
a[i++] = x%10;
x = x/10;
}while(x != 0);
for (int j = 0; j < i; j++)
s = s + a[j] * a[j] * a[j];
if (s == num)
cout << num <<" ";
}
}
运行结果:
经验积累:类的运用在不断提高中。
上机感言:不断巩固才有提高。