定义一个三角形类Ctriangle,求三角形面积和周长。

/*定义一个三角形类Ctriangle,求三角形面积和周长。若这三边无法组成一个三角形则不用计算就退出。*/


#include<iostream>
#include<cmath>
using namespace std;


class Ctriangle{
private:
	double a,b,c;
public:
	Ctriangle(double a,double b,double c)
	{
		if(a+b>c&&a+c>b&&b+c>a)   //判断输入的三边能否组成一个三角形
		{
			this->a=a;
			this->b=b;
			this->c=c;
		}
		else
		{
			cout<<"The three number can't form a triangle!"<<endl;
			exit(0);
		}
	}
	
	
	double Area()             //利用海伦公式求三角形的面积
	{
		double p=Perimeter()/2;
		return sqrt(p*(p-a)*(p-b)*(p-c));
		
	}
	double Perimeter()
	{
		return a+b+c;
		
	}
	void ShowTriangle()
	{
		cout<<"the area of the triangle is:"<<Area()<<endl;
		cout<<"the perimeter of the triangle is:"<<Perimeter()<<endl;
	}
};


int main()
{
	double x,y,z;
	cout<<"input the lengths of the three sides of a triangle:";
	cin>>x>>y>>z;
	Ctriangle C(x,y,z);
	C.ShowTriangle();
	return 0;
}


 

    原文作者:Cheery2018
    原文地址: https://blog.csdn.net/u012495573/article/details/13093477
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞