读书人

c++

发布时间: 2012-03-08 13:30:13 作者: rapoo

c++高手进
小弟刚学c++,原来c没学好有点后悔,请高手指教下
#include <iostream.h>
#include <math.h>
bool Validate(double a,double b,double c);
void CalAndOutputArea(double a,double b,double c);
void main()
{
double a,b,c;
cout<<”请输入三角形的三边长度:”;
cin>>a>>b>>c;
if(Validate(a,b,c))
CalAndOutputArea(a,b,c);
else
cout<<”错误:不能构成三角形!”<<endl;
}
bool Validate(double a,double b,double c)
{
if((a>0)&&(b>0)&&(c>0))
{
if((a+b)<=c) return 0;
if((a+c)<=b) return 0;
if((c+b)<=a) return 0;
return 1; //true
}
else
return 0; //flase
}
void CalAndOutputArea(double a,double b,double c)
{
double s=(a+b+c)/2.0;
double area=sqrt(s*(s-a)*(s-b)*(s-c));
cout<<”三角形(“<<a<<”,”<<b<<”,”<<c<<”)的面积是:”<<area<<endl;
}
编译运行,输入三角形三边长度进行测试。

要求:
上述函数Validate和CclAndOutputArea只能处理三角形的判断和面积计算,若还能处理圆和矩形,利用函数进行重载,编程实现。

[解决办法]
#include <iostream>
#include "math.h"
using namespace std;
#define PI 3.1415926

bool Validate(double a,double b,double c);
bool Validate(double length,double width);
bool Validate(double radius);

void CalAndOutputArea(double a,double b,double c);
void CalAndOutputArea(double length,double width); //you can get the area of the rectangle
void CalAndOutputArea(double radius); //you can get the area of a ring

void main()
{
double a,b,c;
int choice;
do{
cout<<"1.求三角形面积"<<endl;
cout<<"2.求矩形面积"<<endl;
cout<<"3.求圆形面积"<<endl;
cout<<"0.退出"<<endl;
cout<<"please choose"<<endl;
cin>>choice;
if(choice==1)
{
cout<<"请输入三角形的三边长度:"<<endl;
cin>>a>>b>>c;
if(Validate(a,b,c))
CalAndOutputArea(a,b,c);
else
cout<<"错误:不能构成三角形!"<<endl;
}
else if(choice==2)
{
cout<<"请输入矩形的长和宽:"<<endl;
cin>>a>>b;
if(Validate(a,b))
CalAndOutputArea(a,b);
else
cout<<"错误:不能构成矩形!"<<endl;
}
else if(choice==3)
{
cout<<"请输入圆形的半径:"<<endl;
cin>>a;
if(Validate(a))
CalAndOutputArea(a);
else
cout<<"错误:不能构成圆形!"<<endl;
}
else
{
cout<<"now you quit!!!"<<endl;
}
}while(choice);


}


bool Validate(double a,double b,double c)
{
if((a>0)&&(b>0)&&(c>0))
{
if((a+b)<=c) return 0;
if((a+c)<=b) return 0;
if((c+b)<=a) return 0;
return 1; //true
}
else
return 0; //flase
}
bool Validate(double length,double width)
{
if((length>0)&&(width>0))
return 1; //true
else
return 0; //flase
}
bool Validate(double radius)
{
if(radius>0)
return 1;
else
return 0;
}



void CalAndOutputArea(double a,double b,double c)
{
double s=(a+b+c)/2.0;
double area=sqrt(s*(s-a)*(s-b)*(s-c));
cout<<"三角形("<<a<<","<<b<<","<<c<<")的面积是:"<<area<<endl;
}

void CalAndOutputArea(double length,double width)
{
double area=length*width;
cout<<"矩形("<<length<<","<<width<<")的面积是:"<<area<<endl;
}
void CalAndOutputArea(double radius)
{
double area=PI*radius*radius;


cout<<"圆形("<<radius<<")的面积是:"<<area<<endl;
}
[解决办法]
其实你给了范例,再写重载函数挺简单的,就把函数参数改一下就行啦,那个三角形面积求算方法我还不知道呢,向你学习啦


[解决办法]
LZ是哪里不会?函数重载吗?建议好好看看C++ primer!!

读书人网 >C语言

热点推荐