【C++之基于对象】计算3个长方柱的体积

题目要求

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

——谭浩强的《C++面向对象程序设计》第2章习题第6小题

程序

box.h

/*
************************************************************************
@file:    box.h
@date:   2020.11.1
@author: Xiaoxiao
@brief:   定义Box类
@blog:	  https://blog.csdn.net/weixin_43470383/article/details/109412631
************************************************************************
*/

#include <iostream>
using namespace std;

class Box // 声明类类型
{
private: // 声明私有部分
	int length;     // 长方柱的长
	int width;      // 长方柱的宽
	int height;     // 长方柱的高

public: // 声明公用部分
	// 类内声明成员函数
	void set_value();   // 输入长方柱的长、宽、高
	int volume();	// 输出长方柱的体积
};

box.cpp

/*
************************************************************************
@file:    box.cpp
@date:   2020.11.1
@author: Xiaoxiao
@brief:   定义成员函数 set_value() 和 volume()
@blog:	  https://blog.csdn.net/weixin_43470383/article/details/109412631
************************************************************************
*/

#include"box.h"

// 类外定义成员函数
void Box::set_value() // 成员函数定义,由键盘分别输入长方柱的长、宽、高
{
	cin >> length;
	cin >> width;
	cin >> height;
}

int Box::volume() // 成员函数定义,返回长方柱的体积
{
	return (length * width * height);
}

main.cpp

/*
************************************************************************
@file:    main.cpp
@date:   2020.11.1
@author: Xiaoxiao
@brief:   主函数
@blog:	  https://blog.csdn.net/weixin_43470383/article/details/109412631
************************************************************************
*/

#include "box.h"

int main()
{
	Box Box1, Box2, Box3; // 定义Box类的对象Box1, Box2, Box3

	cout << "pls input length, width and height of box1:" << endl;
	Box1.set_value();
	// 调用set_value()函数,由键盘分别输入Box1的长、宽、高
	Box1.volume();
	// 调用volume()函数,输出Box1的体积
	cout << "The volume of box1 is:" << endl << Box1.volume() << endl << endl;

	cout << "pls input length, width and height of box2:" << endl;
	Box2.set_value();
	// 调用set_value()函数,由键盘分别输入Box2的长、宽、高
	Box2.volume();
	// 调用volume()函数,输出Box2的体积
	cout << "The volume of box2 is:" << endl << Box2.volume() << endl << endl;

	cout << "pls input length, width and height of box3:" << endl;
	Box3.set_value();
	// 调用set_value()函数,由键盘分别输入Box3的长、宽、高
	Box3.volume();
	// 调用volume()函数,输出Box3的体积
	cout << "The volume of box3 is:" << endl << Box3.volume() << endl << endl;

	system("pause");
	return 0;
}

运行结果

运行结果

  • 11
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不雨_亦潇潇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值