提问者:小点点

如何计算制作一个空心立方体所需的材料体积


我想计算出创建一个10mm10mm10mm,厚度为1mm的空心立方体所需的材料体积。 我能够使用下面的代码得到空心立方体的体积,但我没有得到如何得到所需的材料的体积来创建一个空心立方体。 我认为这是一个愚蠢的问题,但我没有一个合适的答案。 如有任何建议,我们将不胜感激。 谢谢

#include <iostream>

using namespace std;

class Volume           // Class definition to calculate the volume of the hollow 
{
    public:

    Volume(){};

    double cubeVolume(double length)
    {
        double volume= length * length * length;
        return volume;
    }

    double cube(double num)
    {
        return (num*num*num);
    }

    double getHollowCubeVolume(double length, double thickness)
    {
        double outerVol=cubeVolume(length);
        double innerVol= cube((length-(thickness+thickness)));
    
        double HollowCubeVolume = (cube(outerVol)-cube(innerVol));
    
        return HollowCubeVolume;
    }
};

int main()
{
   cout << "Volume of the material required for hollow cube" << endl; 

   Volume volObj;
   cout<<"Volume of material used to create a hallow cube: "<<volObj.getHollowCubeVolume(10,1)<<endl;

   return 0;
}

共2个答案

匿名用户

首先,请阅读并思考对你的问题的评论。 这些都是很好的建议。

那么,这里有一个解决方案(但请不要只是盲目地使用它。) 您只需要像这样的两个函数:

double cube (double x) {
    return x * x * x;
}

double hollow_cube_volume (double outer_side, double thickness) {
    double inner_side = outer_side - 2 * thickness;
    if (inner_side < 0)
        inner_side = 0.0;
    double volume = cube(outer_length) - cube(inner_side);
    return volume; 
}

就是这样。

你头脑中的公式可能是正确的; 你只是在执行时感到困惑。 还有,这里不需要一个类。

我还添加了一个检查过厚的材料(例如,当我们有一个10mm的立方体,并指定6mm的厚度。) 检查用户错误和错误通常是一个好主意。

匿名用户

首先跟随评论。 看来那只是个愚蠢的错误。 但是错误出现在以下函数中-

double getHollowCubeVolume(double length, double thickness)
{
    double outerVol=cubeVolume(length);
    double innerVol= cube(length-(thickness+thickness));
    
    double HollowCubeVolume = outerVol-innerVol;  //Just take the difference.
                                                  // No need to pass them in cube function again.
    
    return HollowCubeVolume;
}