C++编程,求正方形,长方形,三角形,梯形的周长和面积的程序怎么编写。
- 你的回答被采纳后将获得:
- 系统奖励15(财富值+成长值)+难题奖励30(财富值+成长值)
1个回答
推荐于2017-09-28
展开全部
#include <iostream>
#include <cstring>
using namespace std;
const double pi = 3.14;
class circle
{
public:
circle (double r);
double virtual area();
void area_message(string message);
protected:
double radius;
};
circle :: circle(double r) : radius(r)
{
}
double circle :: area()
{
return pi * radius * radius;
}
void circle :: area_message (string message)
{
cout << message<<area()<<endl;
}
class cylinder : public circle
{
public:
cylinder(double r, double l);
virtual double area();
private:
double length;
};
cylinder :: cylinder (double r, double l) : circle(r),length (l)
{
}
double cylinder :: area()
{
return 2 * pi * radius * (radius + length);
}
class sphere : public circle
{
public :
sphere (double r);
virtual double area();
};
sphere :: sphere (double r) : circle(r)
{
}
double sphere :: area()
{
return 4 * pi * radius * radius ;
}
int main()
{
char shape;
double radius, height;
circle *ptr;
cout << "Enter a shape (1 = circle, 2 = cylinder, 3 = sphere): "<< endl;
cin >> shape;
if(shape > '0' &&shape < '4')
{
cout << "Enter radius" << endl;
cin >> radius;
if(shape == '1' )
{
ptr = new circle(radius);
}
else if(shape == '2')
{
cout << "Enter height" << endl;
cin >> height;
ptr = new cylinder(radius, height);
}
else if (shape == '3')
{
ptr = new sphere (radius);
}
ptr->area_message("The area is : ");
}
else
cout << "Invalid input" << endl;
}
自己改一下吧,模板都有了,把圆换掉。
#include <cstring>
using namespace std;
const double pi = 3.14;
class circle
{
public:
circle (double r);
double virtual area();
void area_message(string message);
protected:
double radius;
};
circle :: circle(double r) : radius(r)
{
}
double circle :: area()
{
return pi * radius * radius;
}
void circle :: area_message (string message)
{
cout << message<<area()<<endl;
}
class cylinder : public circle
{
public:
cylinder(double r, double l);
virtual double area();
private:
double length;
};
cylinder :: cylinder (double r, double l) : circle(r),length (l)
{
}
double cylinder :: area()
{
return 2 * pi * radius * (radius + length);
}
class sphere : public circle
{
public :
sphere (double r);
virtual double area();
};
sphere :: sphere (double r) : circle(r)
{
}
double sphere :: area()
{
return 4 * pi * radius * radius ;
}
int main()
{
char shape;
double radius, height;
circle *ptr;
cout << "Enter a shape (1 = circle, 2 = cylinder, 3 = sphere): "<< endl;
cin >> shape;
if(shape > '0' &&shape < '4')
{
cout << "Enter radius" << endl;
cin >> radius;
if(shape == '1' )
{
ptr = new circle(radius);
}
else if(shape == '2')
{
cout << "Enter height" << endl;
cin >> height;
ptr = new cylinder(radius, height);
}
else if (shape == '3')
{
ptr = new sphere (radius);
}
ptr->area_message("The area is : ");
}
else
cout << "Invalid input" << endl;
}
自己改一下吧,模板都有了,把圆换掉。
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询