PTA 7-5 两点间距离计算(继承)

题目:

代码:

#include <iostream>
#include <cmath>
using namespace std;
class Point_1D

{
protected:
    float x;
public:
    Point_1D()
    {
        x = 0;
    }

    void Set_1D()
    {
        cin >> x;
    }
    
    void distance(const Point_1D& p2)
    {
        float ret =  fabs(p2.x - this->x);
        cout << "Distance from Point " <<
            x << " to Point " << p2.x << " is " <<
            ret << endl;
    }
};

class Point_2D : public Point_1D
{
protected:
    float y;//2D平面上的y坐标

public:
    Point_2D()
    {
        y = 0;
    }
    
    void Set_2D()
    {
        cin >> x >> y;
    }

    void distance(const Point_2D& p2)
    {
        float ret =  sqrt((this->x - p2.x) * (this->x - p2.x) + (this->y - p2.y) * (this->y - p2.y));
        cout << "Distance from Point(" <<
            x << "," << y << ") to Point(" <<
            p2.x << "," << p2.y <<
            ") is " << ret << endl;
    }
};

class Point_3D : public Point_2D
{
protected:
    float z;
public:
    Point_3D()
    {
        z = 0;
    }

    void Set_3D()
    {
        cin >> x >> y >> z;
    }

    void distance(const Point_3D& p2)
    {
        float ret =  sqrt((this->x - p2.x) * (this->x - p2.x) + (this->y - p2.y) * (this->y - p2.y) + (this->z - p2.z) * (this->z - p2.z));
        cout << "Distance from Point(" <<
            x << "," << y << "," <<
            z << ") to Point(" <<
            p2.x << "," << p2.y << "," <<
            p2.z << ") is " << ret << endl;

    }
};

int main()
{
    int input;
    do
    {
        cin >> input;
        switch (input)
        {
        case 1:
        {
            Point_1D p1;
            Point_1D p2;
            p1.Set_1D();
            p2.Set_1D();
            p1.distance(p2);
        }
            break;
        
        case 2:
        {
            Point_2D p3;
            Point_2D p4;
            p3.Set_2D();
            p4.Set_2D(); 
            p3.distance(p4);
        }
            break;
        
        case 3:
        {
            Point_3D p5;
            Point_3D p6;
            p5.Set_3D();
            p6.Set_3D();
            p5.distance(p6);
        }
            break;
        
        case 0:
            break;
        default:
            break;
        }
    } while (input);

    return 0;
}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值