【项目2 - 对象作为数据成员】

问题:本项目设计一个三角形类,其数据成员不再是三角形三条边的边长,而是三角形的三个顶点。利用设计的三角形类,输入三角形的三个顶点,求出其面积、周长,并判断其是否为直角三角形和等腰三角形。

代码:

#include <iostream>
#include <cmath>
#include <Windows.h>
using namespace std;
class CPoint
{
private:
	double x;  // 横坐标  
	double y;  // 纵坐标  
public:
	CPoint(double xx = 0, double yy = 0);
	double distance1(CPoint p) const;   // 两点之间的距离  
	void input();  //以x,y 形式输入坐标点  
	void output(); //以(x,y) 形式输出坐标点  
};
CPoint::CPoint(double xx, double yy)
{
	x = xx;
	y = yy;
}

// 输入坐标点  
void CPoint::input()
{
	char ch;
	cout << "请输入坐标点(格式x,y ):";
	while (1)
	{
		cin >> x >> ch >> y;
		if (ch == ',') break;
		cout << "输入的数据格式不符合规范,请重新输入\n";
	}
}

// 输出坐标点  
void CPoint::output()
{
	cout << "(" << x << ", " << y << ")" << endl;
}

// 求两点之间的距离  
double CPoint::distance1(CPoint p) const
{
	double d;
	d = sqrt((p.x - x)*(p.x - x) + (p.y - y)*(p.y - y));
	return d;
}
class CTriangle
{
public:
	CTriangle(CPoint &X, CPoint &Y, CPoint &Z) :A(X), B(Y), C(Z){} //给出三点的构造函数  
	void setTriangle(CPoint &X, CPoint &Y, CPoint &Z);//  
	float perimeter(void);//计算三角形的周长  
	float area(void);//计算并返回三角形的面积  
	bool isRightTriangle(); //是否为直角三角形  
	bool isIsoscelesTriangle(); //是否为等腰三角形  
private:
	CPoint A, B, C; //三顶点  
};
void CTriangle::setTriangle(CPoint &X, CPoint &Y, CPoint &Z)
{
	A = X;
	B = Y;
	C = Z;
}
float CTriangle::perimeter(void)
{
	double l;
	l = A.distance1(B) + B.distance1(C) + C.distance1(A);
	return l;
}
float CTriangle::area(void)
{
	double a = B.distance1(C), b = C.distance1(A), c = A.distance1(B);
	double s = (a + b + c) / 2;
	return sqrt(s * (s - a) * (s - b) * (s - c));
}
bool CTriangle::isIsoscelesTriangle()
{
	double a = B.distance1(C), b = C.distance1(A), c = A.distance1(B);
	if ((abs(a - b)<1e-7) || (abs(b - c)<1e-7) || (abs(c - a)<1e-7))
		return true;
	else
		return false;
}
bool CTriangle::isRightTriangle()
{
	double a = B.distance1(C), b = C.distance1(A), c = A.distance1(B);
	double max;
	max = a;
	if (a < b)
		max = b;
	if (a < c)
		max = c;
	if (((max == a) && (abs(a*a - b*b - c*c)<1e-7)) || ((max == b) && (abs(b*b - a*a - c*c)<1e-7)) || ((max == c) && (abs(c*c - b*b - a*a)<1e-7)))
		return true;
	else
		return false;
}
int main()
{
	CPoint X(2, 5), Y(5, 2), Z(7, 8);
	CTriangle T(X, Y, Z);  //定义三角形类的一个实例(对象)  
	cout << "该三角形的周长为:" << T.perimeter() << ",面积为:" << T.area() << endl << endl;
	cout << "该三角形" << (T.isRightTriangle() ? "是" : "不是") << "直角三角形" << endl;
	cout << "该三角形" << (T.isIsoscelesTriangle() ? "是" : "不是") << "等腰三角形" << endl;
	system("pause");
	return 0;
}
运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值