C++的题 如下 可以请大家解答一下吗?

建立类cylinder cylinder的构造函数被传递了两个double值,分别表示圆柱体的半径rad和高度height,用类cylinder的成员函数vol()计算圆柱体的体积。
主函数生成1个圆柱体对象数组,里面包含3个圆柱体对象,并统计3个圆柱体体积之和。


#include <iostream>
using namespace std;

class cylinder {
private:
    double rad; // 圆柱体半径
    double height; // 圆柱体高度
public:
    cylinder(double r, double h) { // 构造函数
        rad = r;
        height = h;
    }
    double vol() { // 计算圆柱体体积
        return 3.14 * rad * rad * height;
    }
};

int main() {
    cylinder arr[3] = {cylinder(1.0, 2.0), cylinder(2.0, 3.0), cylinder(3.0, 4.0)}; // 生成圆柱体对象数组
    double sum = 0.0;
    for (int i = 0; i < 3; i++) {
        sum += arr[i].vol(); // 统计3个圆柱体体积之和
    }
    cout << "The sum of the volumes of the cylinders is: " << sum << endl;
    return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 你可以看下这个问题的回答https://ask.csdn.net/questions/7548729
  • 以下回答来自chatgpt:
    #include <iostream>
    using namespace std;
    
    class Cylinder {
    private:
        double radius;
        double height;
    public:
        Cylinder() {}
        Cylinder(double r, double h): radius(r), height(h) {}
        double getVolume() {
            return 3.14 * radius * radius * height;
        }
    };
    
    int main() {
        Cylinder cy1(2.0, 3.0);
        Cylinder cy2(3.0, 4.0);
        Cylinder cy3(4.0, 5.0);
    
        Cylinder arr[3] = {cy1, cy2, cy3};
    
        double sum = 0;
        for (int i = 0; i < 3; i++) {
            sum += arr[i].getVolume();
        }
    
        cout << "The total volume is: " << sum << endl;
    
        return 0;
    }
    

    解析:

    在C++中,我们可以使用类来封装一个对象的数据和行为。这里我们建立一个类Cylinder,表示圆柱体。首先定义类内部的私有变量radiusheight,来表示圆柱体的底面半径和高。接着定义类的构造函数,其中的第一个构造函数不需要任何参数,用于创建一个默认的“空”圆柱体。第二个构造函数则需要传入底面半径和高,用于创建一个具体的圆柱体对象。

    在类中定义了一个getVolume()函数,用于计算圆柱体的体积,并返回结果。在main()函数中首先以不同的参数值创建了三个圆柱体对象,即cy1cy2cy3,然后将它们依次存入一个长度为3的数组arr[]中。最后通过遍历数组,来计算数组中所有圆柱体对象的体积总和,输出结果。

    以上是本题的解答,如果有不清楚的地方,欢迎进一步交流!


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^