R7-4 两点间距离计算

分数 15

切换布局

作者 余春艳   单位 浙江大学

给出下面的一个基类框架:

class Point_1D

{ protected:

    float x;//1D 点的x坐标

public:

    Point_1D(float p = 0.0);

    float distance(const Point_1D & p2);

}

以Point_1D为基类建立一个派生类Point_2D,增加一个保护数据成员:

    float y;//2D平面上点的y坐标

以Point_2D为直接基类再建立一个派生类Point_3D,增加一个保护数据成员:

    float z;//3D立体空间中点的z坐标

生成上述类并编写主函数,根据输入的点的基本信息,建立点对象,并能计算该点到原点的距离。

输入格式: 测试输入包含若干测试用例,每个测试用例占一行(点的类型(1表示1D点,2表示2D点,3表示3D点) 第一个点坐标信息(与点的类型相关) 第二个点坐标信息(与点的类型相关))。当读入0时输入结束,相应的结果不要输出。

输入样例:

1 -1 0

2 3 4 0 0

3 1 2 2 0 0 0

0

输出样例:

Distance from Point -1 to Point 0 is 1

Distance from Point(3,4) to Point(0,0) is 5

Distance from Point(3,3,3) to Point(0,0,0) is 3

#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;

class Point_1D
{
public:
    Point_1D(float p = 0.0)
    {
        x = p;
    }

    float distance(const Point_1D & p2)
    {
        return fabs(x - p2.x);
    }

protected:
    float x;
};

class Point_2D:protected Point_1D
{
public:
    Point_2D(float xx,float yy):Point_1D(xx)
    {
        y = yy;
    }

    float distance(const Point_2D & p2)
    {
        return sqrt((x - p2.x) * (x - p2.x) + (y - p2.y) * (y - p2.y));
    }
protected:
    float y;
};

class Point_3D:protected Point_2D
{
public:
    Point_3D(float xx,float yy,float zz):Point_2D(xx,yy)
    {
        z = zz;
    }

    float distance(const Point_3D & p2)
    {
        return sqrt((x - p2.x) * (x - p2.x) + (y - p2.y) * (y - p2.y) + (z - p2.z) * (z - p2.z));
    }

protected:
    float z;
};

int main()
{
    int ty;
    cin >>ty;
    while(ty)
    {
        if(ty == 1)
        {
            float x1,x2;
            cin >>x1>>x2;
            Point_1D p1(x1),p2(x2);
            cout <<"Distance from Point "<<x1<<" to Point "<<x2<<" is "<<p1.distance(p2)<<endl;
        }
        else if(ty == 2)
        {
            float x1,y1,x2,y2;
            cin >>x1>>y1>>x2>>y2;
            Point_2D p1(x1,y1),p2(x2,y2);
            cout <<"Distance from Point("<<x1<<","<<y1<<") to Point("<<x2<<","<<y2<<") is "<<p1.distance(p2)<<endl;
        }
        else if(ty == 3)
        {
            float x1,y1,z1,x2,y2,z2;
            cin >>x1>>y1>>z1>>x2>>y2>>z2;
            Point_3D p1(x1,y1,z1),p2(x2,y2,z2);
            cout <<"Distance from Point("<<x1<<","<<y1<<","<<z1<<") to Point("<<x2<<","<<y2<<","<<z2<<") is "<<p1.distance(p2)<<endl;
        }
        cin >>ty;
    }
    return 0;
}

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值