C++(四) 多态性与虚函数 输入输出流

记录一下作业

声明抽象基类 Shape,由它派生出 3 个派生类:Circle(圆形)、Rectangle(矩形)、Triangle(三角 形),用一个函数 printArea 分别输出以上三者的面积,3 个图形的数据在定义对象时给定。

#include<iostream>
#include<math.h>
using namespace std;
class shape {
public:
	virtual float printArea() const { return 0.0; }
	virtual void showname()const = 0;
};
class Circle :public shape {
public:
	Circle(float r ) { radius = r; }
	virtual float printArea() const {
		float z;
		z = 3.1415 * radius * radius;
		cout << "area:" << z << endl;
		return z;
	}
	virtual void showname()const { cout << "circle:  "; }
protected:
	float radius;
};
class Rectangle :public shape {
public:
	Rectangle(float a, float b) {
		x = a; y = b;
	}
	virtual void showname()const { cout << "rectangle:   "; }
	virtual float printArea() const {
		cout << "area" << x * y << endl;
		return x * y;
	}
protected:
	float x, y;
};
class Triangle :public shape {
public:
	Triangle(float a, float b, float c) {
		x = a, y = b, z = c;
	}
	virtual void showname()const { cout << "Triangle:     "; }
	virtual float printArea() const {
		float area,s;
		s = (x + y + z) / 2;
		area = sqrt(s*(s-x)*(s-y)*(s-z));
		cout << "area:" << area << endl;
		return area;
	}
protected:
	float x, y, z;
};
void main() {
	Circle cir(5);
	Rectangle rec(2, 3);
	Triangle tri(2, 2, 2);
	shape* p = &cir;
	p->showname();
	p->printArea();
	p = &rec;
	p->showname();
	p->printArea();
	p = &tri;
	p->showname();
	p->printArea();
}

2.输入三角形的三边a, b , c, 计算三角形的面积公式是 s=(a+b+c)/2,AREA=sqrt[s(s-a)(s-b)(s-c)]
    形成三角形的条件是:a+b>c b+c>a,c+a>b编写程序,输入a, b , c,检查a, b , c是否 满足以上条件,如不满足,由 cerr 输出有关出错信息。 

#include<iostream>
#include<math.h>
#include <iomanip>
#include <fstream>
using namespace std;
void main() {
	float a, b, c,s,area;
	cout << "input a,b,c" << endl;
	cin >> a >> b >> c;
	if (a + b > c && b + c > a && c + a > b) {
		s = (a + b + c) / 2;
		area = sqrt(s * (s - a) * (s - b) * (s - c));
		cout << "area: " << area << endl;
	}
	else {
		cerr << "error!" << endl;
	}
}

3.分别遵从以下规则从键盘输入一批数值,要求保留 3 位小数,在输出时上下行小数点对齐。 ①用控制符控制输出格式; ②用流成员函数控制输出格式。  
 ①

#include<iostream>
#include<math.h>
#include <iomanip>
#include <fstream>
using namespace std;
void main() {
	float a, b, c;
	cin >> a >> b >> c;
	cout<<setprecision(3)<<setiosflags(ios::fixed) << setfill(' ') << setw(10) << a << '\n'
		<< setfill(' ') << setw(10) << b << '\n'
		<< setfill(' ') << setw(10) << c << endl;

}


#include<iostream>
#include<math.h>
#include <iomanip>
#include <fstream>
using namespace std;
void main() {
	float a, b, c;
	cin >> a >> b >> c;
	cout.precision(3);
	cout.setf(ios::fixed);
	cout.fill(' ');
	cout.width(10);
	cout << a << endl;
	cout.width(10);
	cout << b << endl;
	cout.width(10);
	cout << c << endl;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值