类 结构体

以下是一个面向对象的C++程序,用于计算并输出三个长方柱的体积:

 

```cpp

#include <iostream>

using namespace std;

 

class RectangularBox{

private:

    double length;

    double width;

    double height;

public:

    void setDimensions(double l, double w, double h){

        length = l;

        width = w;

        height = h;

    }

    double getVolume(){

        return length * width * height;

    }

};

 

int main(){

    RectangularBox box1, box2, box3;

    double l, w, h;

    cout << "Enter dimensions of box 1 (length, width, height): ";

    cin >> l >> w >> h;

    box1.setDimensions(l, w, h);

    cout << "Enter dimensions of box 2 (length, width, height): ";

    cin >> l >> w >> h;

    box2.setDimensions(l, w, h);

    cout << "Enter dimensions of box 3 (length, width, height): ";

    cin >> l >> w >> h;

    box3.setDimensions(l, w, h);

    cout << "The volume of box 1 is " << box1.getVolume() << endl;

    cout << "The volume of box 2 is " << box2.getVolume() << endl;

    cout << "The volume of box 3 is " << box3.getVolume() << endl;

    return 0;

}

```

 

在上面的程序中,我们定义了一个名为RectangularBox的类,它有三个数据成员:length、width和height,分别表示长方柱的长、宽和高。这个类有两个成员函数,setDimensions用于设置长方柱的尺寸,getVolume用于计算长方柱的体积。

 

在主函数中,我们创建了三个RectangularBox对象:box1、box2和box3。然后,通过从键盘读入的尺寸,调用setDimensions函数设置每个长方柱的尺寸。最后,调用getVolume函数计算并输出每个长方柱的体积。

 

注意,我们使用了面向对象的编程方法,将长方柱的尺寸和计算体积的过程封装在一个类中。这样可以使程序更加清晰,易于维护和扩展。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值