程序頭部註釋開始
* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱: 三角形類
* 作 者: 郭廣建
* 完成日期: 2012年 3 月 26 日
* 版 本 號: 1.0
任務描述:
【任務4】設計一個三角形類,能夠輸入三角形的三個頂點,求出其面積、周長,並判斷其是否爲直角三角形和等腰三角形。
提示:(1)這個問題需要用到兩個類,頂點類參照任務3中的CPoint類;(2)三角形類參考下面CTriangle類的聲明;(3)充分利用CPoint類中已有的代碼實現;(4)關於三條邊的處理,可以增加三個私有屬性,在初始化時求出來備用,也可以在需要時計算得到。
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; //三頂點
};
源程序:
#include<iostream>
#include<cmath>
using namespace std;
class CPoint
{
private:
double x; // 橫座標
double y; // 縱座標
public:
CPoint(double xx = 0,double yy = 0);
double Distance(CPoint p) const; // 兩點之間的距離(一點是當前點,另一點爲參數p)
void input(); //以x,y 形式輸入座標點
void output(); //以(x,y) 形式輸出座標點
};
class CTriangle
{
public:
CTriangle(CPoint &X, CPoint &Y, CPoint &Z) : A(X), B(Y), C(Z){} //給出三點的構造函數
void setTriangle(CPoint &X, CPoint &Y, CPoint &Z);//
double perimeter(void);//計算三角形的周長
double area(void);//計算並返回三角形的面積
bool isRightTriangle(); //是否爲直角三角形
bool isIsoscelesTriangle(); //是否爲等腰三角形
private:
CPoint A, B, C; //三頂點
double a, b, c;
};
void CTriangle::setTriangle(CPoint &X, CPoint &Y, CPoint &Z)//
{
A = X;
B = Y;
C = Z;
}
double CTriangle::perimeter(void)//計算三角形的周長
{
a = B.Distance(C),b = C.Distance(A),c = A.Distance(B);
return (a+ b+ c);
}
double CTriangle::area(void)//計算並返回三角形的面積
{
a = B.Distance(C),b = C.Distance(A),c = A.Distance(B);
double q = (a+ b+ c)/2;
return sqrt(q* (q - a)* (q - b)* (q - c));
}
bool CTriangle::isRightTriangle() //是否爲直角三角形
{
a = B.Distance(C),b = C.Distance(A),c = A.Distance(B);
if((a*a + b*b - c*c < 1e-7) || (a*a + c*c - b*b< 1e-7) || (b*b + c*c - a*a < 1e-7))
return true;
else
return false;
}
bool CTriangle::isIsoscelesTriangle() //是否爲等腰三角形
{
a = B.Distance(C),b = C.Distance(A),c = A.Distance(B);
if((a - b < 1e-7) || (b - c < 1e-7) || (c - a < 1e-7))
return true;
else
return false;
}
CPoint::CPoint(double xx ,double yy )
{
x = xx;
y = yy;
}
double CPoint::Distance(CPoint p) const
{
double dis;
dis = sqrt((p.x - x) * (p.x - x) + (p.y - y) * (p.y - y));
return dis;
}
void CPoint::input()
{
char c;
cout << "以x,y形式輸入座標" <<endl;
cin >> x >> c >> y;
while(1)
{
if( c != ',')
cout << "error!";
else
break;
}
}
void CPoint::output()
{
cout << "以(x,y)的形式輸出座標點" <<endl;
cout << '(' << x << ',' << y << ')' <<endl;
}
void main()
{
CTriangle Tr1 (CPoint (0,2), CPoint (0,0), CPoint (2,0));
cout << "三角形的面積是:" << Tr1.area() << " " << "三角形的周長是:" << Tr1.perimeter() <<endl;
cout << "這個三角形" << (Tr1.isRightTriangle()? "是" : "不是" )<< "直角三角形" <<endl;
cout << "這個三角形" << (Tr1.isIsoscelesTriangle()? "是" : "不是") << "等腰三角形"<<endl;
}
運行結果: