谭浩强C++课后习题31——长方柱体积

谭浩强C++课后习题31——长方柱体积

题目描述:需要求3个长方柱的体积,请编写一个基于对象的程序。数据成员包括length(长),width(宽),height(高)。要求用成员函数实现以下功能。
(1)用键盘分别输入3个长方柱的长宽高;
(2)计算长方柱的体积;
(3)输出3个长方柱的体积。

#include<iostream>
using namespace std;
class Box {
private:
	double length;
	double width;
	double height;
public:
	void input();
	double area();
	void showArea();
};
void Box::input() {
	cout << "输入长:";cin >> length;
	cout << "输入宽:";cin >> width;
	cout << "输入高:";cin >> height;
}
double Box::area() {
	return length * width * height;
}
void Box::showArea() {
	cout << "这个长方体的体积为:" << area() << endl;
}
int main() {
	int n;
	cout << "输入长方体个数:";cin >> n;
	Box* box = new Box[n];
	for (int i = 0;i < n;i++) {
		cout << "输入第" << i + 1 << "个长方体的信息:" << endl;
		box[i].input();
		box[i].showArea();
		cout << endl;
	}
	return 0;
}

运行测试结果:
在这里插入图片描述

发布了35 篇原创文章 · 获赞 35 · 访问量 570

猜你喜欢

转载自blog.csdn.net/weixin_45295612/article/details/105309883