编写程序计算长方体的体积python_编写程序一个长方体的长宽高记那个长方体的表面积和体积 要用浮点型数据处理?...
python 版本class Cuboid:def __init__(self, length, width, high):# data must > 0if length <= 0:raise ValueError("length <= 0!")if width <= 0:raise ValueError("width <= 0!")if high <= 0:
python 版本
class Cuboid:
def __init__(self, length, width, high):
# data must > 0
if length <= 0:
raise ValueError("length <= 0!")
if width <= 0:
raise ValueError("width <= 0!")
if high <= 0:
raise ValueError("high <= 0!")
# save the data
self.__length = length
self.__width = width
self.__high = high
# caculate and save the surface area and volume
self.__area = float(2 * (self.__length * self.__width + self.__width * self.__high + self.__high * self.__length))
self.__volume = float(self.__length * self.__width * self.__high)
def get_area(self):
return self.__area
def get_volume(self):
return self.__volume
if __name__ == '__main__':
length = float(input("Please enter the length: "))
width = float(input("Please enter the width: "))
high = float(input("Please enter the high: "))
TestCuboid = Cuboid(length, width, high)
print("Surface area is: ", TestCuboid.get_area())
print("Volume is: ", TestCuboid.get_volume())
测试结果
cpp 版本:
头文件 cuboid.h:
class Cuboid
{
public:
Cuboid(float length, float width, float high);
~Cuboid();
// get surface area
float get_area();
// get volume
float get_volume();
private:
float Length_, Width_, High_, Area_, Volume_;
};
源文件
cuboid.cpp:
#include "cuboid.h"
Cuboid::Cuboid(float length, float width, float high)
{
if (length <= 0)
{
throw "ValueError: length <= 0!";
}
if (width <= 0)
{
throw "ValueError: width <= 0!";
}
if (high <= 0)
{
throw "ValueError: high <= 0!";
}
// save the data
Length_ = length;
Width_ = width;
High_ = high;
// calculate the surface area and volume
Area_ = 2 * (Length_ * Width_ + Width_ * High_ + High_ * Length_);
Volume_ = Length_ * Width_ * High_;
}
Cuboid::~Cuboid(){}
float Cuboid::get_area()
{
return Area_;
}
float Cuboid::get_volume()
{
return Volume_;
}
main.cpp:
#include
#include
int main()
{
float Length, Width, High;
std::cout<
std::cin>>Length;
std::cout<
std::cin>>Width;
std::cout<
std::cin>>High;
try
{
Cuboid TestCuboid(Length, Width, High);
std::cout<
std::cout<
}
catch (char const* e)
{
std::cout<
}
return 0;
}
测试结果:
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)