c++工程文件计算三角形三点计算面积练习题(定义Point类Line类、Triangle类)
如果你是入门c++,想要练习工程文件习题,这个将是个不错的入门题目选择,总代码附在文章底下百度网盘中。
ps:该代码定义的三个三角形点是固定的,如想优化可更改为手动输入三点坐标!!
题目要求:
运行结果:
************************************************************************************************************
我们用到了三个文件:
Test工程文件.cpp 主函数文件 Piont.cpp 成员函数的定义文件 Point.h 成员函数的声明文件
Test工程文件.cpp:
#include "Point.h"
int main()
{
Point p1, p2,p3;
Line x1, x2, x3;
Triangle n;
p1.setXY(0, 0);
p2.setXY(0, 1);
p3.setXY(0, 4);
float a = n.area(x1.juLi(p1, p2), x2.juLi(p1, p3), x3.juLi(p2, p3));
if(a!=0)
{
cout << "三角形面积为:" << a << endl;
}
else
{
cout << "这三个点构不成三角形" << endl;
}
}
Piont.cpp:
#include "Point.h"
#include"Point.h"
void Point::setXY(int x, int y)
{
this->x = x;
this->y = y;
}
int Point::getX()
{
return x;
}
int Point::getY()
{
return y;
}
void Line::setJuLi(Point m, Point n)
{
this->m = m;
this->n = n;
}
float Line::juLi(Point m, Point n)
{
return (float)sqrt((pow((m.getX() - n.getX()), 2) + pow((m.getY() - n.getY()), 2)));
}
void Triangle::setArea(Line a, Line b, Line c)
{
this->a = a;
this->b = b;
this->c = c;
}
float Triangle::area(float a, float b, float c)
{
if ((a + b > c) && (a + c > b) && (b + c > a))
{
float p = (a + b + c) / 2.0;
return sqrt((float)(p * (p - a) * (p - b) * (p - c)));
}
return 0;
}
Piont.h:
#pragma once
#include"math.h"
#include <iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
void setXY(int x, int y);
int getX();
int getY();
};
class Line
{
private:
Point m,n;
public:
void setJuLi(Point m, Point n);
float juLi(Point m, Point n);
};
class Triangle
{
private:
Line a, b, c;
public:
void setArea(Line a, Line b, Line c);
float area(float a,float b,float c);
};
百度网盘提取源码:https://pan.baidu.com/s/1WKljAg_Wb7WlmqrmwMUGww
提取码:exde
************************************************************************************************************