[C++]实验五:掌握类的声明和对象的定义

/*
1.构造计时类
要求:建立Watch类,用来仿效秒表跟踪消逝的时间。
提供两个成员函数Start()与Stop(),分别打开与关闭计时器。
在该类中还包含一个Show()的成员函数,显示消逝的时间(以秒为单位)。
*/

#include <time.h>
#include <iostream>
using namespace std;

class watch {

public:
 void show();
 void start();
 void stop();

private:
 double time;
};


inline void watch::show()
{
 cout << time << endl;
}


inline void watch::start()
{
 clock();
}

inline void watch::stop()
{
 clock_t t;
 t = clock();
 time = (double)t / CLOCKS_PER_SEC; /* 转换成秒 */
}


void main()
{
 watch p1;
 int i=0,j=0;
 p1.start();
 for (; i<100000000 ; i++)
  for (; j<10000000 ; j++)
   (i>j)?i:j;
 p1.stop();
 p1.show();
}

// 清翔兔
// 2005/11/01

/*
2.设计一个立方体类Box,它能计算并输出立方体的体积与表面积。
*/
#include <iostream>
using namespace std;

class Box {
public:
 void init (double,double,double);
 inline double area (){return 2*(l*w+h*l+w*h);};
 double vol(){return w*l*h;};
private:
 double l,w,h;
};

inline void Box::init( double a =0, double b = 0, double c = 0 )
{
 l = a; w = b; h = c;
}

void main ()
{
 Box l1;
 l1.init (1,2,3);
 cout << l1.area() << "/n"
   << l1.vol() << endl;
}

// 清翔兔
// 2005/11/01

/*
3.设计一个采用类结构的方式求n!的程序。
*/

#include <iostream>
using namespace std;

class factorial {
public:
 factorial(unsigned int num): _n(num){};
 unsigned long int facrun (unsigned int);
 unsigned long int fac()  {return facrun (_n);};
private:
 unsigned int _n;
};

unsigned long int factorial::facrun (unsigned int n)
{
 unsigned long int result;
 if(n==1)
  result=1;
 else
  result=facrun(n-1)*n;
 return result;
}

void main()
{
 factorial f1(4);
 cout << f1.fac() << endl;
}

// 清翔兔
// 2005/11/01

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值