7-116 比谁跑的快(类+算法)

来源:互联网 发布:linux awk print 编辑:程序博客网 时间:2024/06/09 15:18

本实例判断两个人谁跑的块,判断标准为各自的平均速度,如果平均速度大,则视为跑得快。
实现过程:
定义类speed,以计算每个人的平均速度。私有变量_time表示时间,_distance表示跑了多远。在成员函数cal_speed()中返回平均速度_distance/_time,代码如下:

#include "StdAfx.h"#include <iostream>using namespace std;class speed{public:    speed(double a,double b)    //构造函数    {        _time=a;                //初始化私有变量        _distance=b;    }    ~speed(){}    double cal_speed()          //计算平均速度    {        return _distance/_time;    }private:    double _time;               //时间    double _distance;           //距离};void main(){    speed peop1(1.5,5000);          //花1.5小时跑了5千米    speed peop2(1,3000);            //花1小时跑了3千米    if(peop1.cal_speed()>peop2.cal_speed()) //如果1大于2        cout<<"第一个人比第二个人跑得快"<<endl;     else if(peop1.cal_speed()<peop2.cal_speed())    //如果2大于1        cout<<"第二个人比第一个人跑的快"<<endl;    else        cout<<"两个人跑的一样快"<<endl;    getchar();}
0 0