用c++定義兩個坐標點,計算兩點間距離;進而計算線段的面積



//本程序有三個層次

//第一層(define_class.h):構造坐標點類,顏色和寬度的結構體,線段類

//第二層(function.h):對上一層聲明的函數進行定義

//第三層(distance.cpp):用類定義對象並初始化對象,對結果進行測試

define_class.h

#if!defined(define_class_H)
#define define_class_h
#include <iostream>
#include <cmath>
using namespace std;
//定義坐標點類
class Point
{
private:
  double X,Y; //橫坐標、縱坐標作為私有變量
public:
  Point(double=0,double=0); //構造函數

  Point(Point &); //復制的構造函數

  void Display() //顯示坐標點
  {
    cout<<X<<","<<Y<<endl;
  }

  double Distance(Point &); //兩點間距離的函數,參數是點類的引用,也可以用友元函數

  int getX()
  {
    return X; //得到橫坐標的值
  }

  int getY()
  {
    return Y; //得到縱坐標的值
  }
};

struct Cow //color和width,結構體,結構體內的變量是public的
{
  int Color;
  int Width;
};

class Line //定義線段類
{
  private:
  Point a,b; //線段類的私有數據成員是點類的對象
  Cow cw; //線段有顏色和寬度
  public:
  Line(Point &,Point &,Cow &); //線段的構造函數,由兩個點、顏色和寬度構成
  void Display();
  Line(Line &); //復制的構造函數
  double Distance(); //兩點間的距離
  double Area(); //線段的面積
};

#endif

function.h

 

#if!defined(function_H)
#define function_H
#include "define_class.h" //包含頭函數
Point::Point(double a,double b) //定義構造函數,前面的頭函數中僅僅聲明了函數
{
  X=a;
  Y=b;
}
Point::Point(Point &a) //定義復制的構造函數
{
  X=a.X;
  Y=a.Y;
}
double Point::Distance(Point &a) //求兩點間的距離
{
  double dis;
  dis=sqrt((X-a.X)*(X-a.X)+(Y-a.Y)*(Y-a.Y));
  return dis;
}
Line::Line(Point &a1,Point &a2,Cow &a3):a(a1),b(a2),cw(a3) //給Line的私有變量初始化
{ //對象間的初始化,因此需要復制的構造函數
}
Line::Line(Line &s) //定義復制的構造函數
{
  a=s.a;
  b=s.b;
  cw=s.cw;
}
void Line::Display() //顯示線段
{
  a.Display();
  b.Display();
  cout<<"Color="<<cw.Color<<","<<"width="<<cw.Width<<endl;
}

Line::Line(Line &m)    //定義Line的復制構造函數

{

      a=m.a;

      b=m.b;

}


double Line::Distance()
{
  double x,y;
  x=a.getX()-b.getX();
  y=a.getY()-b.getY();
  return sqrt(x*x+y*y);
}
double Line::Area()
{
  return cw.Width * Distance();
}
#endif

distance.cpp

 

#include <iostream>
#include <cmath>
#include "function.h"
using namespace std;

 

void main()
{
  Point a;
  Point b(8.9,9.8),c(34.5,67.8);
  a=c;
  a.Display();
  b.Display();

 

  cout<<"兩點之間的距離:"<<a.Distance(b)<<endl;

 

  Cow cw={3,5};

 

  Line s(a,b,cw);

 

  Line s1(s);

 

  s1.Display();

 

  cout<<"線段的長度:"<<s1.Distance()<<endl;
  cout<<"線段的面積:"<<s1.Area()<<endl;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM