程序这样比较好:
#include<iostream>
using namespace std;
#include <cmath>
class tria
{
public:
void setsides(float a,float b,float c);
void print();
private:
float x,y,z;
float area;
};
void tria::setsides(float a,float b,float c)
{
x=a;
y=b;
z=c;
float t=(a+b+c)/2;
area=sqrt(t*(t-a)*(t-b)*(t-c));
}
void tria::print()
{
cout<<"三角形的三条边长分别是:"<<endl;
cout<<x<<"\t"<<y<<"\t"<<z<<endl;
cout<<"三角形面积为:"<<endl;
cout<<area<<endl;
}
void main()
{
int a,b,c;
while(1)
{
cout<<"请输入三角形的三边长:";
cin>>a>>b>>c;
if(a+b<c||b+c<a||a+c<b)
cout<<"这三边组不成三角形,请重新输入!"<<endl;
else
break;
}
tria tr1;
tr1.setsides(a,b,c);
tr1.print();
}
不过,按照C++的编程思想程序应这样写更好:
#include<iostream>
using namespace std;
#include <cmath>
class tria
{
public:
tria(double a,double b,double c);
void jishu();
void print();
private:
float x,y,z;
float area;
};
tria::tria(double a,double b,double c)
{
x=a;
y=b;
z=c;
}
void tria::jishu()
{
float t=(x+y+z)/2;
area=sqrt(t*(t-x)*(t-y)*(t-z));
}
void tria::print()
{
cout<<"三角形的三条边长分别是:"<<endl;
cout<<x<<"\t"<<y<<"\t"<<z<<endl;
cout<<"三角形面积为:"<<endl;
cout<<area<<endl;
}
void main()
{
int a,b,c;
while(1)
{
cout<<"请输入三角形的三边长:";
cin>>a>>b>>c;
if(a+b<c||b+c<a||a+c<b)
cout<<"这三边组不成三角形,请重新输入!"<<endl;
else
break;
}
tria tr1(a,b,c);
tr1.jishu();
tr1.print();
}