编写一个程序,从键盘输入长,宽,高,输出长方体的表面积和体积

这篇博客展示了使用C++编程计算长方体表面积和体积的三种方法:直接计算、函数计算和面向对象编程。通过输入长方体的长、宽和高,程序分别计算并输出表面积和体积。第一种方法中,所有计算都在main函数内完成;第二种方法使用了两个独立的函数get_surface和get_volume;第三种方法采用面向对象,创建Cuboid类并定义了计算表面积和体积的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是我自己写的,有什么不对的请多多指教

下面有三种方法

#include<iostream>
using namespace std;
//方法一
 int main() {
    double length,width,high;
    double surface, volume;
    cout<< "请输入长方体的长,宽和高:" << endl;
    cin >> length >> width >> high;
    surface = 2 * (length * width +  length * high +  width * high);
    volume = length * width * high;
    cout << "表面积为:" << surface << endl;
    cout << "体积为:" << volume << endl;
    return 0;
}

 //方法二
double get_surface(double l, double w, double h) {
    return 2 * (l * w + l * h + w * h);
}
double get_volume(double l, double w, double h) {
    return l * w * h;
}
int main() {
    double length, width, high;
    double surface, volume;
    cout << "请输入长方体的长,宽和高:" << endl;
    cin >> length >> width >> high;
    surface = get_surface(length, width, high);
    volume = get_volume(length, width, high);
    cout << "表面积为:" << surface << endl;
    cout << "体积为:" << volume << endl;
    return 0;
}

 //方法三

//面向对象
class Cuboid {
public:
    Cuboid(double l = 0, double w = 0, double h = 0) //定义一个构造函数,便于后续初始化函数
    {
        length = l;
        width = w;
        high = h;
    }
    double GetSurface()
    {
        return 2 * (length * width + length * high + width * high);
    }
    double GetVolume() {
        return  length * width * high;
    }
private:
    double length, width, high;
};
int main() {
    double i, j, k;
    cout << "请输入长方体的长,宽和高:" << endl;
    cin >> i >> j >> k;
    Cuboid c(i,j,k);
    cout << "表面积为:" << c.GetSurface() << endl;
    cout << "体积为:" << c.GetVolume() << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值