問題及代碼:
/*
*Copyright (c) 2015,煙臺大學計算機學院
*All rights reserved.
*文件名稱:test.cop
*作者:
*完成日期:2015年3月27日
*版本號:v1.0
*
*問題描述:
*輸入描述:
*輸出描述:
#include <iostream>
#include <Cmath>
using namespace std;
class Triangle
{
public:
void setA(double x)
{
a=x;
}
void setB(double y)
{
b=y;
}
void setC(double z)
{
c=z;
};
double getA()
{
return a;
}
double getB()
{
return b;
}
double getC()
{
return c;
}
bool isTriangle();
double perimeter(void);
double area(void);
private:
double a,b,c;
};
int main()
{
Triangle tri1; //定義三角形類的一個實例(對象)
double x,y,z;
cout<<"請輸入三角形的三邊:";
cin>>x>>y>>z;
tri1.setA(x);
tri1.setB(y);
tri1.setC(z); //爲三邊置初值
if(tri1.isTriangle())
{
cout<<"三條邊爲:"<<tri1.getA()<<','<<tri1.getB()<<','<<tri1.getC()<<endl;
cout<<"三角形的周長爲:"<< tri1.perimeter()<<'\t'<<"面積爲:"<< tri1.area()<<endl;
}
else
cout<<"不能構成三角形"<<endl;
return 0;
}
bool Triangle::isTriangle()
{
return (a+b>c&&a+c>b&&b+c>a);
}
double Triangle::perimeter()
{
return a+b+c;
}
double Triangle::area()
{
double p=(a+b+c)/2;
return sqrt(p*(p-a)*(p-b)*(p-c));
}
運行結果: