编程:圆桌子和方桌子
时间: 1ms 内存:128M
描述:
圆桌子(RoundTable)和方桌子(SquareTable),都是桌子(Table)。每种桌子都可以计算其面积。在下面的程序中,通过阅读main函数,可以发现需要将Table类声明为抽象类。在下面框架的引导下,请写出完整的程序,并提交main函数以外的所有代码。
//*****************begin***************
#include <iostream>
#include <iomanip>
using namespace std;
const double PI = 3.1415926;
class Table
{
public:};
//声明圆桌子类
class RoundTable :public Table
{
public:protected:
double radius; //半径
};//声明方桌子类
class SquareTable:public Table
{
public:protected:
double length; //边长
};//*****************end***************
int main( )
{
double r, l;
cin>>r>>l; //输入圆桌子半径和方桌子边长
RoundTable a(r); //创建圆桌子对象
SquareTable b(l); //创建方桌子对象
Table *t; //定义指向抽象类的指针t
t = &a; //t指向了圆桌子对象
cout<<setiosflags(ios::fixed)<<setprecision(2);
cout<<"area of round table: "<<t->area()<<endl; //t->area()返回圆桌子面积
t = &b; //t指向了方桌子对象
cout<<"area of square table: "<<t->area()<<endl; //t->area()返回方桌子面积
return 0;
}
输入:
输入一个圆桌子半径,和一个方桌子的边长
输出:
圆桌子和方桌子的面积
示例输入:
2.13 3.2
示例输出:
area of round table: 14.25
area of square table: 10.24
提示:
参考答案(内存最优[1092]):
#include<stdio.h>
const double PI = 3.1415926;
int main()
{
float a,b;
scanf("%f%f",&a,&b);
printf("area of round table: %.2f\narea of square table: %.2f\n",PI*a*a,b*b);
return 0;
}
参考答案(时间最优[0]):
#include <iostream>
#include <iomanip>
using namespace std;
const double PI = 3.1415926;
//声明抽象基类Table
class Table
{
public:
virtual double area()=0; //纯虚函数
};
//声明圆桌子类
class RoundTable :public Table
{
public:
RoundTable(double r): radius(r) {};
double area()
{
return PI*radius*radius;
}
protected:
double radius;
};
//声明方桌子类类
class SquareTable:public Table
{
public:
SquareTable(double a): length(a) {};
double area()
{
return length*length;
}
protected:
double length; //边长
};
int main( )
{
double r, l;
cin>>r>>l; //输入圆桌子半径和方桌子边长
RoundTable a(r); //创建圆桌子对象
SquareTable b(l); //创建方桌子对象
Table *t; //定义指向抽象类的指针t
t = &a; //t指向了圆桌子对象
cout<<setiosflags(ios::fixed)<<setprecision(2);
cout<<"area of round table: "<<t->area()<<endl; //t->area()返回圆桌子面积
t = &b; //t指向了方桌子对象
cout<<"area of square table: "<<t->area()<<endl; //t->area()返回方桌子面积
return 0;
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。