您的位置:首页 > 其它

点线面子对象法

2016-05-30 17:46 302 查看

建立点,线,面的类(运用的子对象法),并通过点坐标求已知的构成的三角形面积(并没有建立工程,而是直接构造类创建函数):

#include<iostream>
#include<math.h>
#include<stdlib.h>
using namespace std;
class Point
{
public:
Point(float a, float b)
{
x = a;
y = b;
};
void print()
{
cout << "(" << x << "," << y << ")" << endl;
}
private:
float x, y;
};

class Line
{
public:
Line(float x1, float y1, float x2, float y2) :m(x1, y1), n(x2, y2)
{}
double Length(float x1, float y1, float x2, float y2);
void Print();
private:
Point m, n;
};

double Line::Length(float x1, float y1, float x2, float y2)
{
return sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
}
void Line::Print()
{
m.print();
n.print();
}

class Triangle
{
public:
Triangle(float x1, float y1, float x2, float y2, float x3, float y3) :p(x1, y1), q(x2, y2), r(x3, y3),
L1(x1, y1, x2, y2), L2(x1, y1, x3, y3), L3(x2, y2, x3, y3)
{}
double Area(float x1, float y1, float x2, float y2, float x3, float y3);
double Perimeter(float x1, float y1, float x2, float y2, float x3, float y3);
void Print();
private:
Point p, q, r;
Line L1, L2, L3;
};
double Triangle::Perimeter(float x1, float y1, float x2, float y2, float x3, float y3)
{
double j, k, l;
double perimeter;
j = L1.Length(x1, y1, x2, y2);
k = L2.Length(x2, y2, x3, y3);
l = L3.Length(x3, y3, x1, y1);
return perimeter = j + k + l;
}

double Triangle::Area(float x1, float y1, float x2, float y2, float x3, float y3)
{
double s, area;
double j, k, l;
s = Perimeter(x1, y1, x2, y2, x3, y3) / 2;
j = L1.Length(x1, y1, x2, y2);
k = L2.Length(x2, y2, x3, y3);
l = L3.Length(x3, y3, x1, y1);
return area = sqrt(s*(s - j)*(s - k)*(s - l));
}
void Triangle::Print()
{
p.print();
q.print();
r.print();
}
void main()
{
float x1, y1, x2, y2, x3, y3;
cout << "请输入3个点坐标:";
cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;
Point p1(x1, y1), p2(x2, y2), p3(x3, y3);
p1.print();
p2.print();
p3.print();
Line L1(x1, y1, x2, y2), L2(x1, y1, x3, y3), L3(x2, y2, x3, y3);
Triangle T(x1, y1, x2, y2, x3, y3);
cout << "三角形周长:" << T.Perimeter(x1, y1, x2, y2, x3, y3) << endl;
cout << "三角形面积:" << T.Area(x1, y1, x2, y2, x3, y3) << endl;
system("pause");
}
(printf的功能,用法,原型及一些有趣例子)http://gaoxiaodiao.com/p/1.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: